代码之家  ›  专栏  ›  技术社区  ›  Ferrakkem Bhuiyan

如何在php中读取文件并求出该文件的总数

php
  •  0
  • Ferrakkem Bhuiyan  · 技术社区  · 6 年前

    "id,name,value
    1,Dan,150
    2,Peter,300
    3,Mark,400
    4,Victor,600"
    

    此函数用于读取文件:

    function readAFile()
    {
    
        $userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
        //echo fread($userfileInfo, filesize("peopleInformation.txt"));
        $theData = fread($userfileInfo, filesize("peopleInformation.txt"));
        echo $theData;
        fclose($userfileInfo);
    }
    

    输出:

    "id,name,value 1,Dan,150 2,Peter,300 3,Mark,400 4,Victor,600"
    

    3 回复  |  直到 6 年前
        1
  •  0
  •   Illya    6 年前

    尝试使用 preg_match_all 和RegEx

    function readAFile()
    {
    
        $userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
        //echo fread($userfileInfo, filesize("peopleInformation.txt"));
        $theData = fread($userfileInfo, filesize("peopleInformation.txt"));
        echo $theData;
        preg_match_all('/\d+,.+,(\d+)/', $theData, $output);
        $sum = 0;
        foreach($output[1] as $value){
            $sum = $sum + (int) $value;
        };
        //echo "Sum :".$sum;
        fclose($userfileInfo);
    }
        2
  •  1
  •   LF-DevJourney    6 年前

    , 对除第一个标题行外的最后一项求和。

    $lines = file($file_path);
    $lines = array_map(function($v){return explode(",",$v);},array_slice($lines,1));
    echo array_sum(array_column($lines,2)) . PHP_EOL;
    
        3
  •  0
  •   Nawras    6 年前

    fgets 函数逐行读取它。那么你就可以很容易地使用 explode 如下所示:

    $theData = fopen("peopleInformation.txt", "rw"); 
    fgets($theData); //skip the header.
    $sum = 0;
    while (! feof ($my_file)) 
      { 
       $line = fgets($theData); 
       $array_val = explode($line);
       $sum += (int)end($array_val);
      } 
    
    推荐文章