亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為相等的鍵添加多個集合對象值

為相等的鍵添加多個集合對象值

PHP
慕碼人8056858 2024-01-19 15:45:58
我在集合實例中有多個具有相同鍵但不同值的對象。我需要一種在同一對象中添加數量字段鍵值的方法。[    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    }});
查看完整描述

1 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

您可以使用collection 方法?reduce創建一個新集合,您可以在其中添加尚未包含在新集合中的項目,或者對它們的數量求和:

$total = $items->reduce(

? // The function that will insert or add the items together.

? function ($carry, $item) {

? ? if ($carry->has($item->product_id)) {

? ? ? $carry[$item->product_id]->quantity += $item->quantity;

? ? } else {

? ? ? $carry[$item->product_id] = $item;

? ? }

? ? return $carry;

? },?

? // The initial empty collection that will be filled up every iteration.

? collect([])

);


查看完整回答
反對 回復 2024-01-19
  • 1 回答
  • 0 關注
  • 131 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號