Search code examples
phparraysmultidimensional-arraysumgrouping

Group an array of objects by one column and sum another column within each group


After merging two arrays of objects, I get an array structured like this. I would like to group objects with the same ID and add to their quantity

[
    {
        id  :   1
        nome    :   T.SHIRT
        quantita    :   2
    
    }, 
    {
        id  :   2
        nome    :   Sweatshirt
        quantita    :   4
    
    },
  {
        id  :   1
        nome    :   T.SHIRT
        quantita    :   4
    
    }
]

I would like to get an array like this.

[
    {
        id  :   1
        nome    :   T.SHIRT
        quantita    :   6
    
    }, 
  {
        id  :   2
        nome    :   Sweatshirt
        quantita    :   4
    
    },
]   

How can I do this?


Solution

  • The following logic might help you on your way: $store will contain the restructured array with cumulative 'quantita' per 'id'.

    <?php
    $arr = [
        (object)['id' => 1, 'nome' => 'T.SHIRT', 'quantita' => 2,],
        (object)['id' => 2, 'nome' => 'Sweatshirt', 'quantita' => 4,],
        (object)['id' => 1, 'nome' => 'T.SHIRT', 'quantita' => 4,],
    ];
    
    $store = [];
    foreach($arr as $record) {
        if(isset($store[$record->id])) {
            $store[$record->id]->quantita += $record->quantita;
        } else $store[$record->id] = $record;
    }
    

    working demo