array (size=1)
0 => int 0
array (size=1)
0 => string '13.8' (length=4)
array (size=1)
0 => int 0
array (size=1)
0 => string '44.0' (length=4)
array (size=1)
0 => int 0
array (size=1)
0 => int 0
array (size=1)
0 => string '20.2' (length=4)
array (size=1)
0 => int 0
array (size=1)
0 => string '17.8' (length=4)
需要遍历值和总和,然后得到平均值。
我试过这个将值转换为int,这很好:
$changeArray = array_map(
function($value) {
return (int)$value;
}, $totalavgarray);
但是当我尝试这个以获得总和时,我只得到最后一个值:
for ($i = 0; $i < count($changeArray); $i++) {
$sum += $changeArray[$i];<br>
echo $sum;<br>
}
Result = 17
The desired result should be:
SUM = 95.8
AVG = 23.9
var_export($ totalavgarray)结果是:
array ( 0 => 0, )
array ( 0 => '13.8', )
array ( 0 => 0, )
array ( 0 => '44.0', )
array ( 0 => 0, )
array ( 0 => 0, )
array ( 0 => '20.2', )
array ( 0 => 0, )
array ( 0 => '17.8', )
print_r的输出($ totalavgarray);
数组([0] =&gt; 0)
数组([0] =&gt; 13.8)
数组([0] =&gt; 0)
数组([0] =&gt; 44.0)
数组([0] =&gt; 0)
数组([0] =&gt; 0)
数组([0] =&gt; 20.2)
数组([0] =&gt; 0)
数组([0] =&gt; 17.8)
答案 0 :(得分:0)
不要使用for
循环,只需使用foreach
循环。
执行:
<?php
$total = 0;
foreach($changeArray as $value) {
$total += $value;
}
$average = $total/count($changeArray);
echo "Total: {$total}<br>";
echo "Average: {$average}";
?>
答案 1 :(得分:0)
有两个问题:
以下是建议的代码:
$totalavgarray = [ [0], ["13.8"], [0], ["44.0"], [0], [0], ["20.2"], [0], ["17.8"] ];
$sum = $count = 0;
foreach ($totalavgarray as list($val)) {
$sum += $val;
$count += !!$val;
}
$avg = $sum/$count;
echo "Sum: $sum\n"; // 95.8
echo "Avg: $avg\n"; // 23.95