PHP使用递归深度合并多个数组,递归合并嵌套数组

//导入待合并数组,引用$array数组接收
function merge(array &$array,array ...$mergeArray): array
{
    foreach ($mergeArray as $item){
        mergeOne($array,$item); //对每个待合并数组执行合并函数
    }
    return $array;
}

//如果仅有两个数组需要合并,也可以直接使用此函数
function mergeOne(&$array,$pushArray)
{
    foreach ($pushArray as $key=>$item){ //通过键值循环
        if (is_array($item)){ //如果待合并元素同样为数组,进行深度合并
            if(isset($array[$key])&&is_array($array[$key])){ //如果原数组同键名对应元素同样为数组
                mergeOne($array[$key],$item); //递归深度合并
            }else{//如果原数组同键名对应元素不是数组,直接覆盖
                $array[$key]=$item;
            }
        }else{ //如果待合并元素非数组,直接通过键名赋值
            $array[$key]=$item;
        }
    }
}

使用示例

$a=[
    "a"=>10,
    "b"=>[
        "b.a"=>10
    ],
    "c"=>[
        "c.a"=>50,
        "c.b"=>60,
    ]
];
$b=[
    "a"=>20,
    "b"=>30,
    "c"=>[
        "c.a"=>40
    ]
];
$c=[
    "a"=>30,
    "b"=>[
        "b.a"=>40
    ],
    "c"=>[
        "c.a"=>50,
        "c.c"=>100
    ]
];
//合并多个数组
merge($a,$b,$c);
var_dump($a);
//合并两个数组
mergeOne($a,$b);
var_dump($a);

示例结果

//合并$a $b $c
[
  "a" => 30
  "b" => [
    "b.a" => 40
  ]
  "c" => [
    "c.a" => 50
    "c.b" => 60
    "c.c" => 100
  ]
]
//合并$a $b
[
  "a" => 20
  "b" => 30
  "c" =>  [
    "c.a" => 40
    "c.b" => 60
    "c.c" => 100
  ]
]

 

posted on 2022-08-02 00:23  DreamOnTheGo  阅读(234)  评论(0编辑  收藏  举报