我有以下数组
foreach ($reviews as $review){
$sqlreviews[] = array (
'score' => $review['value'] + $review['location'] + $review['service'] + $review['rooms'] + $review['cleanliness'],
);
以下回声输出11 25 25 25
foreach ($sqlreviews as $review1) {
echo"
".$review1['score']."
";
}
如何将上述输出求和并将总数86传递给变量?
答案 0 :(得分:1)
$sum = 0;
foreach ($sqlreviews as $review1) {
$sum += $review1['score'];
}
echo $sum;
答案 1 :(得分:1)
使用PHP 5.5' array_column()功能,您可以执行以下操作:
$total = array_sum(
array_column(
$reviews,
'score'
)
);
对于早期版本的PHP,您可以执行以下操作:
$total = array_sum(
array_map(
function($value) {
return $value['score'];
},
$reviews
)
);
或
$total = array_reduce(
$reviews,
function($runningTotal, $item) {
return $runningTotal + $item['score'];
}
);
答案 2 :(得分:0)
我没有真正了解您的阵列设置方式,但您可以使用array_sum函数输出数组总和:
$a = array_sum($array);
echo $a;
答案 3 :(得分:0)
我猜你有一个像这样的数组=> ['评论'] => ('值' => 0,' location' => 1,' service' => 1,' rooms' => ; 2,' cleanlines' => 2);
$sqlreviews['score'] = $arrayname['reviews']['value'] + $arrayname['reviews']['location'] + $arrayname['reviews']['service'] + $arrayname['reviews']['rooms'] + $arrayname['reviews']['cleanliness'];
如果您只有一组数据,则不需要迭代....