Search code examples
phparraysmultidimensional-arraysumgrouping

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


I have this array

[
    2 => [1160, 1155, '06/26/2013', 32.99],
    3 => [1160, 1155, '06/26/2013', 0.00],
    4 => [1160, 1155, '06/24/2013', 20.99],
    5 => [1160, 1155, '06/24/2013', 10.78],
]

I want, based on "order_id" array[0] same value, to sum of "amount" array[3].


Solution

  • $results = array();
    
    foreach($data as $val){
         if(!array_key_exists($val[0], $results)){
             $results[$val[0]] = 0;
         }
         $results[$val[0]]+= $val[3];
    }
    

    After this $results will contain the totals keyed off of the order_id