[英]Get a total of field values in foreach loop
So my code is 所以我的代码是
if ($activities) { foreach ($activities as $activity) { $price = $activity['price']; if($price) {echo $price;}; } }
and i would like to add the values of the $price field to get a grand total to echo 并且我想添加$ price字段的值以获得总回显
The real work goes on in this line, which increments the total every time the loop iterates (comes around): $total += $price;
真正的工作在这一行继续进行,每次循环迭代时都会增加总数(到处): $total += $price;
$total = 0;
if ($activities) {
foreach ($activities as $activity) {
$price = $activity['price'];
if($price) {
echo $price; // do you still need this?
$total += $price;
}
}
}
echo $total;
Why use a loop? 为什么要使用循环? I would use array_sum()
. 我会使用array_sum()
。
$total = array_sum(array_filter(array_values($activities)));
array_values
returns all the values. array_values
返回所有值。 array_filter
filters out anything that evaluates to false (like null or 0). array_filter
过滤掉任何计算结果为false的内容(如null或0)。 array_sum
adds them up. array_sum
将它们加起来。
Functional programming is your friend. 功能编程是你的朋友。 :-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.