douba2705 2018-08-12 13:43
浏览 115

PHP - 如何使用从文本文件中获取的数字进行计算?

So I have a task where I should read a text file in php, containing students IDs and their grades, separated by vertical lines. It looks something like that:

12345|4|2|1|0|4 
45678|1|2|3|4|4 
78901|5|5|5|5|4 

The program should print the amount of students there are on the file, which I managed to do by simply echoing the amount of lines. However, I should also print the sum of the grades for each student, and I simply can't find a way to do it. Do I get the characters by order on the line or something similar? I've been struggling with this for a day now and I only got as far as this:

<?php 

$file="exam.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}


echo "total_students was $linecount:";
$homepage = file_get_contents('exam.txt');
echo $homepage;


?>

This code only prints the page and the amount of lines, nothing more.

  • 写回答

1条回答 默认 最新

  • douke6857 2018-08-13 14:32
    关注

    So after I was guided in the right direction I managed to come up with a solution!

    <?php 
    
    $file="exam.txt";
    $linecount = 0;
    $handle = fopen($file, "r");
    while(!feof($handle)){
      $line = fgets($handle);
      $linecount++;
    }
    
    
    echo "total_students was $linecount:
    ";
    
    
    $lines = file('exam.txt');
    $sum = 0 ;
    
    foreach ($lines as $line){
    $var = explode("|", $line);
    $sum = $var[1]+$var[2]+$var[3]+$var[4]+$var[5];
    $all += $sum;
    echo "$var[0]: $sum points
    ";
    }
    
    $average = $all / $linecount;
    echo "The average score was $average points."
    
    ?>
    

    I exploded each line as an array divided by the "|" symbol, then I printed the student ID from the [0] of the array, and summed the rest. After that I summed the sums and thus found the average.

    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏