我有一个格式为
的文件1 52
2 456
3 4516
5 4545
6 41
读取文件的最快方法是什么,并在PHP的第二列中获取min / max / avg值?
答案 0 :(得分: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;
答案 1 :(得分: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
}