Search code examples
phparraysmultidimensional-arraysumgrouping

Group 2d array data by one column and sum other columns in each group (separately)


I need to group the data in my indexed array of indexed arrays by the first column values (id column). Within each group, I need to find the sum of the second column and find the sum of the third column.

Sample input:

[
    [111, 5, 3],
    [111, 3, 7],
    [111, 2, 1],
    [222, 5, 3],
]

Desired result:

[
    111 => [10, 11]
    222 => [5, 3]
]

Solution

  • You'd have to do this manually using a loop. Something like this should work:

    $result = array();
    
    foreach( $input as $row) {
        $id = array_shift( $row);
    
        foreach( $row as $key => $value) {
    
            $result[ $id ][ $key ] = 
                ( isset( $result[ $id ][ $key ]) ? 
                      $result[ $id ][ $key ] + $value : 
                      $value
                );
        }
    }
    

    Output:

    array(2) {
      [111]=>
      array(2) {
        [0]=>
        int(10)
        [1]=>
        int(11)
      }
      [222]=>
      array(2) {
        [0]=>
        int(5)
        [1]=>
        int(3)
      }
    }
    

    Demo