-
慕的地10843
请始终与我们分享您的尝试。它对我们有很大帮助。您可以使用:$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'));
-
繁花不似锦
/* 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;}
-
开满天机
另一种选择是使用 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"];});