Search code examples
phparraysmultidimensional-arrayarray-mergearray-sum

Merge indexed array of associative arrays and sum the values of recurring keys


I have a multidimensional array that looks like this:

Array
(
    [0] => Array
    (
        [GB] => 20827
        [US] => 73
        [ES] => 23
        [AU] => 15
        [DE] => 12
        [MY] => 4
        [QA] => 1
        [VN] => 1
        [SK] => 1
        [FJ] => 1
        [ME] => 1
        [TR] => 1
        [LV] => 1
    )

    [1] => Array
    (
        [GB] => 15070
        [US] => 3920
        [IE] => 1711
        [PH] => 1071
        [MT] => 578
        [AU] => 423
        [HR] => 241
        [ZA] => 210
        [FR] => 139
    )
)

I want to create a new array with all of the associative elements in each array of the multidimensional array and sum the values of duplicated keys.

Desired result from sample input:

array (
  'GB' => 35897,
  'US' => 3993,
  'ES' => 23,
  'AU' => 438,
  'DE' => 12,
  'MY' => 4,
  'QA' => 1,
  'VN' => 1,
  'SK' => 1,
  'FJ' => 1,
  'ME' => 1,
  'TR' => 1,
  'LV' => 1,
  'IE' => 1711,
  'PH' => 1071,
  'MT' => 578,
  'HR' => 241,
  'ZA' => 210,
  'FR' => 139,
)

Solution

  • Look through each of the sub-arrays, and then loop through the key/value pairs. Add them up in a $final array:

    $final = [];
    foreach($masterArray as $subArray) {
        foreach($subArray AS $key => $value) {
            $final[$key] = isset($final[$key])
                ? $final[$key] + $value
                : $value;
        }
    }
    

    Working example: https://3v4l.org/6XBbD