dongyuyi5680
2019-06-12 18:31
浏览 34
已采纳

PHP中多维数组的求和值

Supposing I have this array in PHP:

Array
(
    [0] => Array
        (
            [name] => Banana
            [quantity] => 124
        )
    [1] => Array
        (
            [name] => Cherry
            [quantity] => 24
        )
    [2] => Array
        (
            [name] => Apple
            [quantity] => 224
        )

)

How can I sum the number with the key quantity ?

Thanks.

图片转代码服务由CSDN问答提供 功能建议

假设我在PHP中有这个数组:

  Array \  n(
 [0] =>数组
(
 [名称] =>香蕉
 [数量] => 124 
)
 [1] =>数组
(
 [  name] => Cherry 
 [数量] => 24 
)
 [2] =>数组
(
 [名称] => Apple 
 [数量] => 224 
  )
 
)
   
 
 

如何使用密钥 quantity 对数字求和? < p>谢谢。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doudiandi6967 2019-06-12 18:34
    已采纳

    Please, always share with us what you have tried.

    It help us a lot.

    You can use:

    $arr = [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
    
    $sum = 0;
    foreach ($arr as $item) {
        $sum += $item['quantity'];
    }
    

    Or (PHP 5.5+):

    $sum = array_sum(array_column($arr, 'quantity'));
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongtazu3080 2019-06-12 18:40
    /*
        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;
    }
    
    评论
    解决 无用
    打赏 举报
  • duanben1324 2019-06-12 18:43

    Another option is to use the reduce function:

    $arr= [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
    
    echo array_reduce($arr, function($sum, $elem) {
        return $sum += $elem["quantity"];
    });
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题