phparraysmultidimensional-arraysumgrouping

Group rows of a 2d array by a column and sum another column in each group


I have this array:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 10
  )
  [2] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 18
  )
)

How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?

Like this:

Array (
  [0] => Array (
    [TaxeName] => TPS
    [TaxeAmount] => 7
    [Price] => 14
  )
  [1] => Array (
    [TaxeName] => TVQ
    [TaxeAmount] => 9.975
    [Price] => 28
  )
)

Solution

  • It can be done with a nested foreach:

    $original = array(.......); // your current array
    $newArr = array();
    
    foreach($original as $origVal){
        $exists = false;
        foreach($newArr as $key => $newVal){
            if($newVal['TaxeName'] == $origVal['TaxeName']){
                $newArr[$key]['Price'] += $origVal['Price'];
                $exists = true;
                break;
            }
        }
    
        if(!$exists){
            $newArr[] = $origVal;
        }
    }
    

    Outputs

    Array
    (
        [0] => Array
            (
                [TaxeName] => TPS
                [TaxeAmount] => 7
                [Price] => 14
            )
    
        [1] => Array
            (
                [TaxeName] => TVQ
                [TaxeAmount] => 9.975
                [Price] => 28
            )
    
    )