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

如何基于关联集合/数组更新Laravel集合/数组值,未匹配项设为0

问题描述

我需要求取两个Laravel集合的差值,现有两个集合/数组定义如下:

$first = [
    "name" => "Test A",
    "scores" => [
        ["name" => "Values", "points" => 9],
        ["name" => "Algebra", "points" => 6],
        ["name" => "Science", "points" => 5],
        ["name" => "Total", "points" => 20]
    ]
];
$second = [
    "name" => "Test A",
    "scores" => [
        ["name" => "Values", "points" => 5],
        ["name" => "Algebra", "points" => 8],
        ["name" => "Total", "points" => 13]
    ]
];

我的目标是以第一个集合为基准生成新集合,保留第二个集合中已匹配科目的points值,第一个集合存在但第二个集合缺失的科目,points值设为0,预期输出结果如下:

[
    "name" => "Test A",
    "scores" => [
        ["name" => "Values", "points" => 5],
        ["name" => "Algebra", "points" => 8],
        ["name" => "Science", "points" => 0],
        ["name" => "Total", "points" => 13]
    ]
]

我尝试使用diffKeys方法实现:

$collection_new = $collection_1['scores']->diffKeys($collection_2['scores']);
dd($collection_new->all());

最终得到的输出不符合预期,该如何正确实现需求?


解答

diffKeys方法是按集合的索引键做对比,你两个scores数组的元素都用数字索引,并未以科目名称作为键,因此无法按科目匹配得到正确结果。

正确实现代码如下:

// 将第二个数组的成绩转为以科目名为键的集合,方便快速查询
$secondScoreMap = collect($second['scores'])->keyBy('name');

// 以第一个数组为基准生成结果
$result = [
    'name' => $first['name'],
    'scores' => collect($first['scores'])->map(function ($scoreItem) use ($secondScoreMap) {
        $scoreItem['points'] = $secondScoreMap->get($scoreItem['name'], ['points' => 0])['points'];
        return $scoreItem;
    })->toArray()
];

// 输出验证
dd($result);

执行代码后得到的$result完全符合预期输出。


内容的提问来源于stack exchange,提问作者user3233787

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:45:02