foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
}
例如:
文档1 = 8
文档 2 = 7
文档 3 = 1
我要计算$value,所以结果是8+7+1 = 16。我该怎么办?
谢谢。
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
在你的情况下,如果你想使用 foreach 循环而不是
$sum = 0;
foreach($group as $key => $value) {
$sum += $value;
}
echo $sum;
但是,如果您想使用数组的直接总和而不是在下面查看您的解决方案:
$total = array_sum($group);
因为只有数组循环的总和是浪费时间。
http://php.net/manual/en/function.array-sum.php
array_sum — 计算数组中值的总和
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
上面的示例将输出:
sum(a) = 20
sum(b) = 6.9
您可以使用array_sum()
.
$total = array_sum($group);
利用+=
$val = 0;
foreach($arr as $var) {
$val += $var;
}
echo $val;
$total=0;
foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
$total+= $value;
}
echo $total;