PHP 深度合并多维数组 wpjam_array_merge
我们知道 array_merge_recursive()
不会进行键名覆盖,而是将多个相同键名的值递归合并成一个数组。
$ar1 = array("color" => array("red", "green"), "aa");
$ar2 = array("color" => array( "green", "blue"), "bb");
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
输出结果:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 2 => 'green',
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
其实我们希望子数组里面的相同的值覆盖,据此我们写了一个 wpjam_array_merge
函数,用来深度合并多维数组:
function wpjam_array_merge($arr1, $arr2){
$merged = $arr1;
foreach($arr2 as $key => &$value){
if(is_array($value) && isset($merged[$key]) && is_array($merged[$key])){
$merged[$key] = wpjam_array_merge($merged[$key], $value);
}elseif(is_numeric($key)){
if(!in_array($value, $merged)) {
$merged[] = $value;
}
}else{
$merged[$key] = $value;
}
}
return $merged;
}
得到的结果是:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
WPJAM Basic 已经集成了该函数,只要激活即可使用。