function doSomething($config = null) {
$default = [
'name' => 'Chan',
'age' => 36
];
if ($config !== null) {
$default = array_merge($default, $config);
}
var_dump($default);
}
doSomething(); // This one get name is chan and age is 36
doSomething(['age' => 10]); // This one get name is chan and age is 10
我想要一个默认的配置数据,如果我将一些参数传递给函数,请使用array_merge进行部分更新,但它不适用于子数组。
function doSomething($config = null) {
$default = [
'name' => 'Chan',
'age' => 36,
'sub' => [
'a' => 1,
'b' => 2
]
];
if ($config !== null) {
$default = array_merge($default, $config);
}
var_dump($default);
}
doSomething(); // This one sub is ['a' => 1, 'b' => 2]
doSomething(['sub' => ['a' => 3]]); // This one sub is ['a' => 3]
如何在子阵列上部分替换配置?
答案 0 :(得分:1)
function doSomething($config = []) {
$default = [
'name' => 'Chan',
'age' => 36,
'sub' => [ 'a' => 1, 'b' => 2 ]
];
if (!empty($config)) {
$default = array_replace_recursive($default, $config);
}
print_r($default);
}
//doSomething(); // This one sub is ['a' => 1, 'b' => 2]
doSomething(['sub' => ['a' => 3]]);
输出:
Array
(
[name] => Chan
[age] => 36
[sub] => Array
(
[a] => 3
[b] => 2
)
)
答案 1 :(得分:0)
递归替换默认配置:
<?php
function updater( $old, $new ) {
if ( is_array(current($old)) && is_array(current($new)) ) {
return updater($old, $new);
} else {
return array_merge($old, $new);
}
}
function doSomething($config = null) {
$default = [
'name' => 'Chan',
'age' => 36,
'sub' => [
'a' => 1,
'b' => 2
]
];
if ($config !== null) {
foreach( $config as $key => $value ) {
$default[$key] = updater($default[$key], $value);
}
}
print_r($default);
}
doSomething();
doSomething(['sub' => ['a' => 3]]);
结果:
Array
(
[name] => Chan
[age] => 36
[sub] => Array
(
[a] => 1
[b] => 2
)
)
Array
(
[name] => Chan
[age] => 36
[sub] => Array
(
[a] => 3
[b] => 2
)
)
答案 2 :(得分:0)
<?php
$default_data = [
"name" => "Meraj",
"age" => 21,
"education" => [
"school" => "JMI",
"college" => "GGSIPU"
]
];
function modifyArrayData($default_data, $new_data = null)
{
foreach ($new_data as $key => $value) {
if (!is_array($value)) {
$default_data[$key] = $value;
} else {
$default_data[$key] =modifyArrayData($default_data[$key], $value);
}
}
return $default_data;
}
$new_data = ["name" => "Coder", "education" => ["school" => "Jamia"]];
$test = modifyArrayData($default_data, $new_data);
var_dump($test);
由于我们需要修改的数据可能是未知深度的多维数组,因此我们需要分别使用递归和句柄。