Search code examples
phparraysmultidimensional-arraysumgrouping

Group values in an array of single-element arrays by second level key and sum values within each group


The input array:

[
    [1 => 2],
    [1 => 2],
    [2 => 1],
    [3 => 1],
]

I want this output:

[
    [1 => 4],
    [2 => 1],
    [3 => 1],
]

Solution

  • $result = array();
    foreach ($input as $subarray) {
        foreach ($subarray as $key => $value) {
            if (isset($result[$key])) {
                $result[$key][$key] += $value;
            } else {
                $result[$key] = array($key => $value);
            }
        }
    }
    $result = array_values($result); // Convert from associative array to indexed array