项目中有一个默认配置数组,想要自定义一个数组,然后自定义数组中的键,覆盖默认的配置数组的键。
这种配置,我们经常在 js 中见到:
$.extend(true, target, obj1[, obj2, ...])
第一个参数,设置为 true,表示递归复制
但在 php 中,想起来,突然觉得很生疏,不知道有没有,然后翻看了下手册,回顾了下 array_* 函数:
测试了 4 个:
array_merge
array_merge_recursive
array_replace
array_replace_recursive
最终发现:
array_replace_recursive
完美符合我们想要的结果!省了自己写!
下面是测试:
$a = [
'name' => 'dongxuemin',
'age' => 30,
'jobs' => [
'name' => 'pin',
'time' => 1,
'three' => [
'xxx' => '11',
]
],
];
$b = [
'jobs' => [
'name' => 'xue',
'three' => [
'xxx' => '22',
]
],
];
$c = array_merge($a, $b);
$d = array_merge_recursive($a, $b);
$e = array_replace($b);
$f = array_replace_recursive($a, $b);
echo '<pre>';
var_export($c);
echo '<br>';
var_export($d);
echo '<br>';
var_export($e);
echo '<br>';
var_export($f);
echo '</pre>';
exit;
/*
// 输出结果:
array (
'name' => 'dongxuemin',
'age' => 30,
'jobs' =>
array (
'name' => 'xue',
'three' =>
array (
'xxx' => '22',
),
),
)
array (
'name' => 'dongxuemin',
'age' => 30,
'jobs' =>
array (
'name' =>
array (
0 => 'pin',
1 => 'xue',
),
'time' => 1,
'three' =>
array (
'xxx' =>
array (
0 => '11',
1 => '22',
),
),
),
)
array (
'jobs' =>
array (
'name' => 'xue',
'three' =>
array (
'xxx' => '22',
),
),
)
array (
'name' => 'dongxuemin',
'age' => 30,
'jobs' =>
array (
'name' => 'xue',
'time' => 1,
'three' =>
array (
'xxx' => '22',
),
),
)
*/