1

我有一个格式的文件

1    52
2    456
3    4516
5    4545
6     41

什么是读取文件并在 PHP 的第二列中获取 min/max/avg 值的最快方法?

4

2 回答 2

1

类似于以下内容,<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

于 2012-04-25T22:29:30.227 回答
1

从@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
}
于 2012-04-26T04:37:52.083 回答