为了账号安全,请及时绑定邮箱和手机立即绑定

为相等的键添加多个集合对象值

为相等的键添加多个集合对象值

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 关注
  • 30 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信