我想找出值的方差,但我无法正确找到平均值。我添加了爆炸,因为在使用array_sum时,它显示错误,即array_sum()期望参数1为数组,给定字符串。
<html><body>
<?php
$ap = '36.222.198.197.166.140';
$counte =0;$sum=0;
$file_handle = fopen("results.csv", "r");
while ( $line_of_text = fgetcsv($file_handle)){
if ($line_of_text[2] == $ap) {
$counte++;
$van = explode(" ",$line_of_text[3]);
$fMean = array_sum($van) / count($van);
print_r ($van);
}
}
fclose($file_handle);
?>
</body></html>
这是csv格式 - time1,time2,mac,2.4ghz,5ghz
1485874798, 1485878398, 36.222.198.197.166.140, -73, -72
1485874798, 1485878398, 148.180.15.200.220.114, -69, -65
1485874798, 1485878398, 148.180.15.194.95.70, -74, 0
1485874798, 1485878398, 0.36.108.195.38.227 0, -63
1485874798, 1485878398, 36.222.198.197.171.88, -73, -69
1485874798, 1485878398, 24.100.114.205.236.242, 0, 0
1485874798, 1485878398, 0.36.108.195.34.153 0, 0
1485874798, 1485878398, 148.180.15.200.220.118, -74, -64
1485874798, 1485878398, 0.36.108.195.38.220 0, -74
1485874798, 1485878398, 216.199.200.202.199.48, 0, -67
1485874798, 1485878398, 148.180.15.193.105.60, -62, -66
1485874798, 1485878398, 156.28.18.195.202.230, -74, -74
1485874798, 1485878398, 148.180.15.200.220.126, -73, -71
1485874798, 1485878398, 0.36.108.195.38.219 0, -60
1485874798, 1485878398, 0.36.108.195.38.217, -45, -63
1485874798, 1485878398, 0.36.108.195.38.218, -71, -73
1485874798, 1485878398, 0.36.108.195.38.216, 0, -74
1485874798, 1485878398, 0.36.108.195.33.193, 0, 0
1485874798, 1485878398, 148.180.15.200.220.190, -74, 0
1485874798, 1485878398, 36.222.198.197.166.138, -74, -68
1485874798, 1485878398, 0.36.108.195.33.197, 0, -72
1485874798, 1485878398, 36.222.198.197.171.18, -74, -74
1485874798, 1485878398, 0.36.108.195.33.58, 0, 0
1485874798, 1485878398, 0.36.108.195.33.199, -74, 0
1485874798, 1485878398, 0.36.108.195.31.214, -63, -69
1485874798, 1485878398, 148.180.15.200.220.198, 0, -69
1485874798, 1485878398, 0.36.108.195.31.218 -74, 0
1485874798, 1485878398, 0.36.108.195.35.135, 0, 0
1485874798, 1485878398, 36.222.198.197.171.68, -74, -67
1485874798, 1485878398, 148.180.15.194.97.50, -74, 0
1485874798, 1485878398, 216.199.200.202.200.152, -74, -74
1485874798, 1485878398, 148.180.15.193.134.238, -70, 0
1485874798, 1485878398, 0.36.108.195.35.131, 0, -42
1485874798, 1485878398, 36.222.198.197.170.202, -73, -73
1485874798, 1485878398, 148.180.15.200.220.78, -74, -70
1485874798, 1485878398, 36.222.198.197.170.100, -73, -66
1485874798, 1485878398, 0.36.108.195.30.123, -74, -66
答案 0 :(得分:1)
您的数据存在不一致之处:
表达式explode(" ",$line_of_text[3]);
毫无意义,因为$line_of_text[3]
是一个数字,而不是空格。在此结果上使用count
也没有意义,因为您想要计算行数,而不是其中一个字段中的某些内容。
以下是更正后的版本:
$ap = '36.222.198.197.166.140';
$file_handle = fopen("results.csv", "r");
while ( $line_of_text = fgetcsv($file_handle)){
if ($line_of_text[2] == $ap) $van[] = $line_of_text[3];
}
fclose($file_handle);
$fMean = array_sum($van) / count($van);
然后计算方差如下:
$variance = array_sum(array_map(function ($x) use ($fMean) {
return pow($x - $fMean, 2);
}, $van)) / count($van);