将特定字段的数组中的对象分组

Groups objects in arrays for a specific field

合并两个对象数组后,我得到一个结构如下的数组。我想将具有相同 ID 的对象分组并添加到它们的数量

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

我想要一个这样的数组。

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

我该怎么做?

以下逻辑可能对您有所帮助:$store 将包含每个 'id'.

累积 'quantita' 的重组数组
<?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;
}

工作demo