How to sum all column values in multi-dimensional array?

后端 未结 20 2526
花落未央
花落未央 2020-11-22 00:57

How can I add all the columnar values by associative key? Note that key sets are dynamic.

Input array:

Arr         


        
20条回答
  •  梦如初夏
    2020-11-22 01:25

    Here is a solution similar to the two others:

    $acc = array_shift($arr);
    foreach ($arr as $val) {
        foreach ($val as $key => $val) {
            $acc[$key] += $val;
        }
    }
    

    But this doesn’t need to check if the array keys already exist and doesn’t throw notices neither.

提交回复
热议问题