Search code examples
phparraysmultidimensional-arraysumgrouping

Group rows of 2d array by one column and sum another column


I have an array:

Array 
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )

[1] => Array
    (
        [setid] => 2
        [income] => 120
    )

[2] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

I need to find entries with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:

Array
(
[0] => Array
    (
        [setid] => 2
        [income] => 220
    )

[1] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

Does someone know a sophisticated solution for my problem or do I have to take the long road and do every step manually?


Solution

  • Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.

    $result = array();
    foreach ($array as $val) {
        if (!isset($result[$val['setid']]))
            $result[$val['setid']] = $val;
        else
            $result[$val['setid']]['income'] += $val['income'];
    }
    $result = array_values($result); // reindex array