我已经运行了SUM子数组,它匹配了像这样的
键 $totals = array();
$count_loops = 0 ;
// First get our totals.
foreach ($average as $subKey => $subArray) {
foreach ($subArray as $k => $v) {
// Add the column to our total.
$totals[$k] = isset($totals[$k] ) ? $totals[$k] + $v / $count_loops : $v;
}
}
并像这样返回总数组
Array
(
[john_total] => 519.44
[adam_total] => 1664.64
[sara_total] => 1237.53
}
但是我希望在使用count循环除以总和数之后返回平均值,但是它返回错误的平均值...如果我删除此代码/ $count_loops
总结好......那怎么做呢
答案 0 :(得分:0)
认为您可以在PHP中使用:array_sum和count函数:
$totals = array();
$count_loops = 0 ;
// First get our totals.
foreach ($average as $subKey => $subArray) {
$totals[$k] = array_sum($subArray) / count($subArray);
}
答案 1 :(得分:0)
使用array_sum
和count
array_sum将给出总结果的总和。
和count将给出元素的总数。
和平均值是A计算的"中心"一组数字的值。
所以
$average = array_sum($array) / count($array);
答案 2 :(得分:0)
请注意在代码的这一点上将要进行的计算。
$totals[$k] = isset($totals[$k] ) ? $totals[$k] + $v / $count_loops : $v;
我宁愿你拥有它
$totals[$k] = isset($totals[$k] ) ? ( $totals[$k] + $v ) / $count_loops : $v;
(5 + 2.5)/ 2 => 7.5 / 2 = 3.75
5 +(2.5 / 2)=> 5 + 1.25 = 6.25
这些计算是相同的数字,但取决于运算符优先级。见http://php.net/manual/en/language.operators.precedence.php