array_merge_recursive / array_replace_recursive

array_merge_recursive(array ...$arrays): array — array_replace_recursive(array ...$arrays): array

嵌套数组的递归合并与替换:merge_recursive 把同键标量聚合成数组(port 变成 [3306,5432]),replace_recursive 则让后者深度覆盖前者。两者都不改原数组,行为差异是配置合并的关键考点。

C C23

C23
#include <stdio.h>
#include <string.h>
#include "cJSON.h"

// merge_recursive 对应物:同键标量碰撞聚合成含两者的数组,a 在前
static cJSON *merge_recursive(const cJSON *a, const cJSON *b) {
    if (cJSON_IsObject(a) && cJSON_IsObject(b)) {
        cJSON *out = cJSON_Duplicate(a, 1);
        const cJSON *bv = NULL;
        cJSON_ArrayForEach(bv, b) {
            const cJSON *av = cJSON_GetObjectItemCaseSensitive(a, bv->string);
            if (av) {
                cJSON_ReplaceItemInObject(out, bv->string, merge_recursive(av, bv));
            } else {
                cJSON_AddItemToObject(out, bv->string, cJSON_Duplicate(bv, 1));
            }
        }
        return out;
    }
    if (a && b) { // 两个标量:包成二元数组
        cJSON *arr = cJSON_CreateArray();
        cJSON_AddItemToArray(arr, cJSON_Duplicate(a, 1));
        cJSON_AddItemToArray(arr, cJSON_Duplicate(b, 1));
        return arr;
    }
    return cJSON_Duplicate(a ? a : b, 1);
}

// replace_recursive 对应物:b 逐键胜出,嵌套对象递归深入
static cJSON *replace_recursive(const cJSON *a, const cJSON *b) {
    if (cJSON_IsObject(a) && cJSON_IsObject(b)) {
        cJSON *out = cJSON_Duplicate(a, 1);
        const cJSON *bv = NULL;
        cJSON_ArrayForEach(bv, b) {
            const cJSON *av = cJSON_GetObjectItemCaseSensitive(a, bv->string);
            if (av) {
                cJSON_ReplaceItemInObject(out, bv->string, replace_recursive(av, bv));
            } else {
                cJSON_AddItemToObject(out, bv->string, cJSON_Duplicate(bv, 1));
            }
        }
        return out;
    }
    return cJSON_Duplicate(b ? b : a, 1);
}

int main(void) {
    cJSON *a = cJSON_Parse("{\"db\":{\"host\":\"localhost\",\"port\":3306},\"debug\":true}");
    cJSON *b = cJSON_Parse("{\"db\":{\"port\":5432,\"ssl\":\"on\"}}");
    char *m = cJSON_PrintUnformatted(merge_recursive(a, b));
    char *r = cJSON_PrintUnformatted(replace_recursive(a, b));
    printf("%s\n%s\n", m, r);
    cJSON_free(m); cJSON_free(r);
    cJSON_Delete(a); cJSON_Delete(b);
    return 0;
}
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

C++ C++26

C++26
#include <iostream>
#include "nlohmann/json.hpp"
using nlohmann::json;

// merge_recursive 对应物:同键标量碰撞聚合成含两者的数组,a 在前
json merge_recursive(const json &a, const json &b) {
    if (a.is_object() && b.is_object()) {
        json out = a;
        for (auto &[k, v] : b.items()) {
            if (out.contains(k) && out[k].is_object() && v.is_object())
                out[k] = merge_recursive(out[k], v);
            else if (out.contains(k) && !v.is_object())
                out[k] = json::array({out[k], v});
            else
                out[k] = v;
        }
        return out;
    }
    return b;
}

// replace_recursive 对应物:b 逐键胜出,嵌套对象递归深入
json replace_recursive(const json &a, const json &b) {
    if (a.is_object() && b.is_object()) {
        json out = a;
        for (auto &[k, v] : b.items()) {
            out[k] = (out.contains(k) && out[k].is_object() && v.is_object())
                         ? replace_recursive(out[k], v)
                         : v;
        }
        return out;
    }
    return b;
}

int main() {
    json a = {{"db", {{"host", "localhost"}, {"port", 3306}}}, {"debug", true}};
    json b = {{"db", {{"port", 5432}, {"ssl", "on"}}}};
    std::cout << merge_recursive(a, b).dump() << "\n";
    std::cout << replace_recursive(a, b).dump() << "\n";
    return 0;
}
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

C# v11.0.100

v11.0.100
using System.Text.Json;

var a = new SortedDictionary<string, object> {
    ["db"] = new SortedDictionary<string, object> { ["host"] = "localhost", ["port"] = 3306 },
    ["debug"] = true,
};
var b = new SortedDictionary<string, object> {
    ["db"] = new SortedDictionary<string, object> { ["port"] = 5432, ["ssl"] = "on" },
};

// 标准库无深合并:手写递归
SortedDictionary<string, object> Merge(SortedDictionary<string, object> x, SortedDictionary<string, object> y) {
    var out_ = new SortedDictionary<string, object>(x);
    foreach (var (k, v) in y) {
        if (out_.TryGetValue(k, out var old) && old is SortedDictionary<string, object> od && v is SortedDictionary<string, object> vd)
            out_[k] = Merge(od, vd);
        else if (out_.ContainsKey(k) && v is not SortedDictionary<string, object>)
            out_[k] = new List<object> { old!, v }; // 标量碰撞聚合成含两者的数组
        else
            out_[k] = v;
    }
    return out_;
}

SortedDictionary<string, object> Replace(SortedDictionary<string, object> x, SortedDictionary<string, object> y) {
    var out_ = new SortedDictionary<string, object>(x);
    foreach (var (k, v) in y)
        out_[k] = out_.TryGetValue(k, out var old) && old is SortedDictionary<string, object> od && v is SortedDictionary<string, object> vd
            ? Replace(od, vd)
            : v; // b 深度胜出
    return out_;
}

Console.WriteLine(JsonSerializer.Serialize(Merge(a, b)));
Console.WriteLine(JsonSerializer.Serialize(Replace(a, b)));
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Go v1.27.4

v1.27.4
package main

import (
	"encoding/json"
	"fmt"
)

func merge(a, b map[string]any) map[string]any {
	out := map[string]any{}
	for k, v := range a {
		out[k] = v
	}
	for k, v := range b {
		old, exists := out[k]
		ao, aok := old.(map[string]any)
		bo, bok := v.(map[string]any)
		switch {
		case !exists:
			out[k] = v
		case aok && bok: // 两边都是嵌套 map:递归
			out[k] = merge(ao, bo)
		default: // 其他碰撞:聚合成含两者的数组,a 在前
			out[k] = []any{old, v}
		}
	}
	return out
}

func replace(a, b map[string]any) map[string]any {
	out := map[string]any{}
	for k, v := range a {
		out[k] = v
	}
	for k, v := range b {
		if ao, aok := out[k].(map[string]any); aok {
			if bo, bok := v.(map[string]any); bok {
				out[k] = replace(ao, bo)
				continue
			}
		}
		out[k] = v // b 胜出
	}
	return out
}

func main() {
	a := map[string]any{"db": map[string]any{"host": "localhost", "port": 3306}, "debug": true}
	b := map[string]any{"db": map[string]any{"port": 5432, "ssl": "on"}}
	ma, _ := json.Marshal(merge(a, b))
	ra, _ := json.Marshal(replace(a, b))
	fmt.Println(string(ma))
	fmt.Println(string(ra))
}
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    @SuppressWarnings("unchecked")
    static Map<String, Object> merge(Map<String, Object> a, Map<String, Object> b) {
        Map<String, Object> out = new LinkedHashMap<>(a);
        for (var e : b.entrySet()) {
            Object old = out.get(e.getKey());
            boolean bothMaps = old instanceof Map && e.getValue() instanceof Map;
            if (bothMaps)
                out.put(e.getKey(), merge((Map<String, Object>) old, (Map<String, Object>) e.getValue()));
            else if (out.containsKey(e.getKey()))
                out.put(e.getKey(), List.of(old, e.getValue())); // 标量碰撞 -> 含两者的数组,a 在前
            else
                out.put(e.getKey(), e.getValue());
        }
        return out;
    }

    @SuppressWarnings("unchecked")
    static Map<String, Object> replace(Map<String, Object> a, Map<String, Object> b) {
        Map<String, Object> out = new LinkedHashMap<>(a);
        for (var e : b.entrySet()) {
            Object old = out.get(e.getKey());
            out.put(e.getKey(), old instanceof Map && e.getValue() instanceof Map
                    ? replace((Map<String, Object>) old, (Map<String, Object>) e.getValue())
                    : e.getValue()); // b 深度胜出
        }
        return out;
    }

    // 迷你紧凑 JSON 序列化器:LinkedHashMap 保插入序
    static String json(Object v) {
        if (v instanceof Map<?, ?> m) {
            StringBuilder sb = new StringBuilder("{");
            int i = 0;
            for (var e : m.entrySet())
                sb.append(i++ > 0 ? "," : "").append('"').append(e.getKey()).append("\":").append(json(e.getValue()));
            return sb.append("}").toString();
        }
        if (v instanceof List<?> l) {
            StringBuilder sb = new StringBuilder("[");
            int i = 0;
            for (Object o : l) sb.append(i++ > 0 ? "," : "").append(json(o));
            return sb.append("]").toString();
        }
        if (v instanceof String s) return "\"" + s + "\"";
        return v.toString();
    }

    public static void main(String[] args) {
        Map<String, Object> dbA = new LinkedHashMap<>(); // 保持插入序
        dbA.put("host", "localhost");
        dbA.put("port", 3306);
        Map<String, Object> a = new LinkedHashMap<>();
        a.put("db", dbA);
        a.put("debug", true);
        Map<String, Object> dbB = new LinkedHashMap<>();
        dbB.put("port", 5432);
        dbB.put("ssl", "on");
        Map<String, Object> b = new LinkedHashMap<>();
        b.put("db", dbB);
        System.out.println(json(merge(a, b)));
        System.out.println(json(replace(a, b)));
    }
}
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

JavaScript v26.13.1

v26.13.1
const a = { db: { host: "localhost", port: 3306 }, debug: true };
const b = { db: { port: 5432, ssl: "on" } };
const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);

// merge_recursive 对应物:同键标量碰撞聚合成含两者的数组,a 在前
function mergeRecursive(x, y) {
  const out = { ...x };
  for (const [k, v] of Object.entries(y)) {
    if (isPlain(out[k]) && isPlain(v)) out[k] = mergeRecursive(out[k], v);
    else if (k in out) out[k] = [out[k], v];
    else out[k] = v;
  }
  return out;
}

// replace_recursive 对应物:b 逐键胜出,嵌套对象递归深入
function replaceRecursive(x, y) {
  const out = { ...x };
  for (const [k, v] of Object.entries(y)) {
    out[k] = isPlain(out[k]) && isPlain(v) ? replaceRecursive(out[k], v) : v;
  }
  return out;
}

console.log(JSON.stringify(mergeRecursive(a, b)));
console.log(JSON.stringify(replaceRecursive(a, b)));
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

PHP v8.6.0

v8.6.0
$a = ["db" => ["host" => "localhost", "port" => 3306], "debug" => true];
$b = ["db" => ["port" => 5432, "ssl" => "on"]];
// merge_recursive:同名字符串键的标量碰撞被合并成含两者的【数组】
echo json_encode(array_merge_recursive($a, $b)), "\n";
// replace_recursive:$b 逐键深度胜出
echo json_encode(array_replace_recursive($a, $b)), "\n";
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Python v3.15.2

v3.15.2
import json

a = {"db": {"host": "localhost", "port": 3306}, "debug": True}
b = {"db": {"port": 5432, "ssl": "on"}}

def merge_recursive(x, y):
    out = dict(x)
    for k, v in y.items():
        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
            out[k] = merge_recursive(out[k], v)
        elif k in out:
            out[k] = [out[k], v]  # 标量碰撞聚合成含两者的列表,a 在前
        else:
            out[k] = v
    return out

def replace_recursive(x, y):
    out = dict(x)
    for k, v in y.items():
        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
            out[k] = replace_recursive(out[k], v)
        else:
            out[k] = v  # b 深度胜出
    return out

print(json.dumps(merge_recursive(a, b), separators=(",", ":")))
print(json.dumps(replace_recursive(a, b), separators=(",", ":")))
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Rust v1.99.1

v1.99.1
use serde_json::{json, Value};

// merge_recursive 对应物:同键标量碰撞聚合成含两者的数组,a 在前
fn merge_recursive(a: &Value, b: &Value) -> Value {
    if let (Some(x), Some(y)) = (a.as_object(), b.as_object()) {
        let mut out = x.clone();
        for (k, v) in y {
            match out.get(k) {
                Some(old) if old.is_object() && v.is_object() => {
                    out.insert(k.clone(), merge_recursive(old, v));
                }
                Some(old) => {
                    out.insert(k.clone(), json!([old, v]));
                }
                None => {
                    out.insert(k.clone(), v.clone());
                }
            }
        }
        return Value::Object(out);
    }
    b.clone()
}

// replace_recursive 对应物:b 逐键胜出,嵌套对象递归深入
fn replace_recursive(a: &Value, b: &Value) -> Value {
    if let (Some(x), Some(y)) = (a.as_object(), b.as_object()) {
        let mut out = x.clone();
        for (k, v) in y {
            match out.get(k) {
                Some(old) if old.is_object() && v.is_object() => {
                    out.insert(k.clone(), replace_recursive(old, v));
                }
                _ => {
                    out.insert(k.clone(), v.clone()); // b 胜出
                }
            }
        }
        return Value::Object(out);
    }
    b.clone()
}

fn main() {
    let a = json!({"db": {"host": "localhost", "port": 3306}, "debug": true});
    let b = json!({"db": {"port": 5432, "ssl": "on"}});
    println!("{}", merge_recursive(&a, &b));
    println!("{}", replace_recursive(&a, &b));
}
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

TypeScript v26.13.1

v26.13.1
type Obj = Record<string, unknown>;
const a: Obj = { db: { host: "localhost", port: 3306 }, debug: true };
const b: Obj = { db: { port: 5432, ssl: "on" } };
const isObj = (v: unknown): v is Obj => v !== null && typeof v === "object" && !Array.isArray(v);

// merge_recursive 对应物:同键标量碰撞聚合成含两者的数组,a 在前
function mergeRecursive(x: Obj, y: Obj): Obj {
  const out: Obj = { ...x };
  for (const [k, v] of Object.entries(y)) {
    const old = out[k];
    if (isObj(old) && isObj(v)) out[k] = mergeRecursive(old, v);
    else if (k in out) out[k] = [old, v];
    else out[k] = v;
  }
  return out;
}

// replace_recursive 对应物:b 逐键胜出,嵌套对象递归深入
function replaceRecursive(x: Obj, y: Obj): Obj {
  const out: Obj = { ...x };
  for (const [k, v] of Object.entries(y)) {
    const old = out[k];
    out[k] = isObj(old) && isObj(v) ? replaceRecursive(old, v) : v;
  }
  return out;
}

console.log(JSON.stringify(mergeRecursive(a, b)));
console.log(JSON.stringify(replaceRecursive(a, b)));
输出
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

语言差异说明

C:cJSON 上手写递归;标量碰撞包成二元数组,a 在前;cJSON 对象按插入序输出。

C++:nlohmann json 手写递归;对象底层是 std::map,键有序输出天然确定。

C#:标准库无深合并;SortedDictionary 键有序保证输出确定。

Go:map 手写递归;json.Marshal 对 map 键排序,输出确定。

Java:手写递归+迷你序列化器;LinkedHashMap 保插入序(Map.of 序不保证,示例显式 put)。

JavaScript:手写递归;'...' spread 只浅合一层是常见坑。

PHP:核心差异一对——merge_recursive 同字符串键的标量碰撞聚合成数组(port→[3306,5432],配置合并里反复合并会把值累积成越来越长的数组,是常见事故源);replace_recursive 深度覆盖(b 赢)。两者都不改原数组;merge_recursive 对整数键会像 array_merge 一样重排,replace_recursive 保留原键。数字键在 merge_recursive 下始终 append,字符串键才触发聚合。

Python:手写递归;'|' 合并运算符(3.9+)只浅合一层,深合并需手写。

Rust:serde_json Value 手写递归;校验器 cargo 模式开 preserve_order 保插入序,与 PHP 输出一致。

TypeScript:同 JavaScript;Obj 类型标注。