Search code examples
phparraysmultidimensional-arraysumgrouping

Group 2d array by one column and sum multiple columns within each group


I need to group the row data in my 2d array by one column and sum the other columns individually to produce a new 2d array with potentially fewer rows.

In my case, I need to calculate the sums of [num] and [price] by each [group].

[
    ['group' => 'Apple', 'num' => 5, 'price' => 10],
    ['group' => 'Apple', 'num' => 2, 'price' => 8],
    ['group' => 'Orange', 'num' => 4, 'price' => 6],
    ['group' => 'Orange', 'num' => 12, 'price' => 24],
]

And the result would be like:

[
    ['group' => 'Apple', 'num' => 7, 'price' => 18],
    ['group' => 'Orange', 'num' => 16, 'price' => 30],
]

Solution

  • Simple loop and assocative arrays will do the job:

    $result = Array();
    foreach($array as $row) {
       if(!isset($result[ $row['group'] ])) {
           $result[ $row['group'] ] = $row;
           continue ;
       }
       $result[ $row['group'] ]['num'] += $row['num'];
       $result[ $row['group'] ]['price'] += $row['price'];
    }
    $result = array_values($result);