快速查找文件中的最小/最大/平均值


fast way to find find min/max/avg value in file

>我有一个格式的文件

1    52
2    456
3    4516
5    4545
6     41

PHP 中读取文件并获取第二列中的最小/最大/平均值的最快方法是什么?

类似于

以下内容,其中<filename>是文件的路径。

$file = fopen('<filename>', 'r');
$a = 0;
$b = 0;
$first = true;
while (fscanf($file, '%d%d', $a, $b)) {
    if ($first)
    {
        $min = $b;
        $max = $b;
        $total = $b;
        $count = 1;
        $first = false;
    }
    else
    {
        $total += $b;
        if ($b < $min) $min = $b;
        if ($b > $max) $max = $b;
        $count++;
    }
}
$avg = $total / $count;

演示:http://ideone.com/rWbqm

从@mellamokb代码中进行了一些性能改进:

$file = fopen('<filename>', 'r'); 
$a = $b = 0; 
if (fscanf($file, '%d%d', $a, $b))
{
   $min = $max = $total = $b; 
   $count = 1;
   while (fscanf($file, '%d%d', $a, $b))
   { 
      $total += $b; 
      if ($b < $min) $min = $b; 
      else if ($b > $max) $max = $b; 
      ++$count; 
   } 
   $avg = $total / $count;
}
else
{
   // Do something here as there is nothing in the file
}