如何在Laravel中从Collection集合提取指定数组,过滤保留目标字段
实现代码
假设你的原始集合变量为$originalCollection,可以通过链式调用Laravel集合内置方法完成需求:
$processed = $originalCollection // 遍历集合项,仅保留pending、ongoing下的amount字段 ->map(function ($item, $key) { if (in_array($key, ['pending', 'ongoing'])) { return ['amount' => $item['amount']]; } return $item; }) // 新增discount_total字段,值为原price_total的数值 ->put('discount_total', $originalCollection->get('price_total')) // 删除原有的price_total字段 ->forget('price_total');
Laravel 8及以上版本支持箭头函数,可简化为:
$processed = $originalCollection ->map(fn ($item, $key) => in_array($key, ['pending', 'ongoing']) ? ['amount' => $item['amount']] : $item) ->put('discount_total', $originalCollection->get('price_total')) ->forget('price_total');
如果需要最终输出为数组格式,在调用链末尾追加->toArray()即可。
如需兼容pending/ongoing不存在amount字段的场景,避免报错,可以用data_get辅助函数取值:
return ['amount' => data_get($item, 'amount', 0)];
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

