假设我在PHP中有此数组:
Array
(
[0] => Array
(
[name] => Banana
[quantity] => 124
)
[1] => Array
(
[name] => Cherry
[quantity] => 24
)
[2] => Array
(
[name] => Apple
[quantity] => 224
)
)
如何用键quantity
将数字相加?
谢谢。
答案 0 :(得分:4)
请随时与我们分享您的尝试。
它对我们有很大帮助。
您可以使用:
$arr = [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
$sum = 0;
foreach ($arr as $item) {
$sum += $item['quantity'];
}
或者(PHP 5.5 +):
$sum = array_sum(array_column($arr, 'quantity'));
答案 1 :(得分:0)
/*
Receives a Multidemensional Array (Matrix) and returns the sum of quantity.
Returns -1 on fail.
*/
function SumKeyOfArray($Matrix)
{
if(!empty($Matrix))
{
$sum = 0;
foreach($Matrix as $array)
{
if(isset($array['quantity']))
$sum = $sum + $array['quantity'];
}
return $sum;
}
return -1;
}
答案 2 :(得分:0)
另一种选择是使用reduce函数:
$arr= [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
echo array_reduce($arr, function($sum, $elem) {
return $sum += $elem["quantity"];
});