我在集合實例中有多個具有相同鍵但不同值的對象。我需要一種在同一對象中添加數量字段鍵值的方法。[ 0 => { +"product_id": 1 +"quantity": "50" +"price": "25.00" }, 1 => { +"product_id": 3 +"quantity": "50" +"price": "75.00" }, 2 => { +"product_id": 2 +"quantity": "50" +"price": "50.00" }, 3 => { +"product_id": 3 +"quantity": "50" +"price": "75.00" } ]生成的實例應將數量添加到相同的項目鍵中,如下所示。[ 0 => { +"product_id": 1 +"quantity": "50" +"price": "25.00" }, 1 => { +"product_id": 2 +"quantity": "50" +"price": "50.00" } 2 => { +"product_id": 3 +"quantity": "100" +"price": "75.00" }]我嘗試迭代所有對象并添加/編輯對象,如下所示。我不確定這是否是 Laravel 集合中的最佳實踐方式。$newItems = [];$items->each(function ($item, $key) use ($newItems) { $existId = array_column($newItems, 'id'); if($existId){ // add quantity to the existing item } else { // push item to items array }});
為相等的鍵添加多個集合對象值
慕碼人8056858
2024-01-19 15:45:58