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

如何在Laravel/PHP中正确合并两个多维数组?

多维数组合并:保留默认值,覆盖指定子键

我有两个多维数组:

$options = [
    "type" => "identity",
    "document" => [
        "required" => true,
        "allowed_countries" => null,
        "restricted_countries" => null,
        "allowed_types" => null
    ],
    "send_email" => false
    // .... 更多选项
];

$user_options = [
    "type" => "identity",
    "document" => [
        "required" => false
    ],
    "send_email" => false
];

希望合并后得到如下结果:用用户数组的值覆盖默认数组的对应键,同时保留默认数组中未被覆盖的所有键值

[
    "type" => "identity",
    "document" => [
        "required" => false,
        "allowed_countries" => null,
        "restricted_countries" => null,
        "allowed_types" => null
    ],
    "send_email" => false       
];  

但尝试多种方法都未达到预期:

  • 使用array_merge会丢失document子数组中的allowed_countries等未被用户数组指定的键;
  • 使用array_merge_recursive会将required这类重复键的值合并为数组,而不是覆盖;
  • 尝试Laravel集合的merge方法也无法实现需求。

解决方案:实现递归覆盖合并函数

需要自定义一个递归合并函数,核心逻辑是以默认数组为基础,用用户数组的值逐层覆盖,遇到子数组则递归处理,代码如下:

function recursiveMerge(array $default, array $user): array
{
    foreach ($user as $key => $value) {
        // 如果双方当前键都是数组,则递归合并子数组
        if (is_array($value) && isset($default[$key]) && is_array($default[$key])) {
            $default[$key] = recursiveMerge($default[$key], $value);
        } else {
            // 否则直接用用户值覆盖默认值
            $default[$key] = $value;
        }
    }
    return $default;
}

// 使用示例
$result = recursiveMerge($options, $user_options);
print_r($result);

这个函数会完全符合需求:子数组中存在的键会被用户值覆盖,未被用户指定的键则保留默认数组的原值,既不会丢失键,也不会把值合并为数组。

如果是Laravel项目,也可以直接使用这个函数,或者基于Collection封装该逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:20:15