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

marknt15 picture marknt15 · Sep 30, 2009 · Viewed 225.6k times · Source

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

Input array:

Array
(
    [0] => Array
        (
            [gozhi] => 2
            [uzorong] => 1
            [ngangla] => 4
            [langthel] => 5
        )

    [1] => Array
        (
            [gozhi] => 5
            [uzorong] => 0
            [ngangla] => 3
            [langthel] => 2
        )

    [2] => Array
        (
            [gozhi] => 3
            [uzorong] => 0
            [ngangla] => 1
            [langthel] => 3
        )
)

Desired result:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

Answer

potashin picture potashin · Dec 8, 2014

You can use array_walk_recursive() to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).

$final = array();

array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

Example with array_walk_recursive() for the general case

Also, since PHP 5.5 you can use the array_column() function to achieve the result you want for the exact key, [gozhi], for example :

array_sum(array_column($input, 'gozhi')); 

Example with array_column() for the specified key

If you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :

$final = array_shift($input);

foreach ($final as $key => &$value){
   $value += array_sum(array_column($input, $key));
}    

unset($value);

Example with array_column() in case all inner arrays have the same keys

If you want a general-case solution using array_column() then at first you may consider to get all unique keys , and then get the sum for each key :

$final = array();

foreach($input as $value)
    $final = array_merge($final, $value);

foreach($final as $key => &$value)
    $value = array_sum(array_column($input, $key));

unset($value);

Example with array_column() for the general case