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

后端 未结 20 2822
花落未央
花落未央 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:39

    Another version, with some benefits below.

    $sum = ArrayHelper::copyKeys($arr[0]);
    
    foreach ($arr as $item) {
        ArrayHelper::addArrays($sum, $item);
    }
    
    
    class ArrayHelper {
    
        public function addArrays(Array &$to, Array $from) {
            foreach ($from as $key=>$value) {
                $to[$key] += $value;
            }
        }
    
        public function copyKeys(Array $from, $init=0) {
            return array_fill_keys(array_keys($from), $init);
        }
    
    }
    

    I wanted to combine the best of Gumbo's, Graviton's, and Chris J's answer with the following goals so I could use this in my app:

    a) Initialize the 'sum' array keys outside of the loop (Gumbo). Should help with performance on very large arrays (not tested yet!). Eliminates notices.

    b) Main logic is easy to understand without hitting the manuals. (Graviton, Chris J).

    c) Solve the more general problem of adding the values of any two arrays with the same keys and make it less dependent on the sub-array structure.

    Unlike Gumbo's solution, you could reuse this in cases where the values are not in sub arrays. Imagine in the example below that $arr1 and $arr2 are not hard-coded, but are being returned as the result of calling a function inside a loop.

    $arr1 = array(
        'gozhi' => 2,
        'uzorong' => 1,
        'ngangla' => 4,
        'langthel' => 5
    );
    
    $arr2 = array(
       'gozhi' => 5,
       'uzorong' => 0,
       'ngangla' => 3,
       'langthel' => 2
    );
    
    $sum = ArrayHelper::copyKeys($arr1);
    
    ArrayHelper::addArrays($sum, $arr1);
    ArrayHelper::addArrays($sum, $arr2);
    

提交回复
热议问题