You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:06:07