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

Laravel中合并数组并保留唯一键的实现方案咨询

解决方法

方法一:先转成键值对映射再构建结果

先将两个数组转换为以唯一ID为键的映射数组,再遍历ID生成目标结构,这种方法不依赖两个数组的元素顺序,只要ID对应即可:

$prices = [
    ['112802' => "500000"],
    ['113041' => "1000000"],
];

$notes = [
    ['112802' => "note 2"],
    ['113041' => "note 1"],
];

// 转换为[id => price]的映射
$priceMap = collect($prices)->flatMap(fn($item) => $item)->toArray();
// 转换为[id => note]的映射
$noteMap = collect($notes)->flatMap(fn($item) => $item)->toArray();

// 生成目标数组
$result = collect($priceMap)->map(function ($price, $id) use ($noteMap) {
    return [
        'id' => $id,
        'price' => $price,
        'note' => $noteMap[$id] ?? '', // 兼容note不存在的情况
    ];
})->toArray();

print_r($result);

方法二:按顺序遍历数组(适用于两个数组元素顺序完全对应)

如果$prices和$notes中对应位置的元素ID完全一致,可以直接遍历数组,提取每个元素的键和值:

$prices = [
    ['112802' => "500000"],
    ['113041' => "1000000"],
];

$notes = [
    ['112802' => "note 2"],
    ['113041' => "note 1"],
];

$result = [];
foreach ($prices as $index => $priceItem) {
    $id = array_key_first($priceItem); // 获取当前元素的唯一ID
    $noteItem = $notes[$index];
    $result[] = [
        'id' => $id,
        'price' => $priceItem[$id],
        'note' => $noteItem[$id],
    ];
}

print_r($result);

原代码问题说明

你之前用zip方法的问题在于,它只是将两个集合对应位置的元素简单合并成子数组,不会保留原数组的键信息,也无法直接将键转换为id字段,所以得不到期望的结构化结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:25:29