对于我试图传递给请求的数据而不是替换数组中的现有数据,它正在替换数组中的第一个值。有人能告诉我这里我做错了什么吗?
private function validParams($overrides = [])
{
return array_replace_recursive([
// More fields,
'posts' => [
1 => [
'field1' => ...,
'field2' => [],
'field3' => [],
'field4' => [],
'users' => [1, 2],
'field6' => ...,
]
],
], $overrides);
}
$this->validParams([
'posts' => [
1 => [
'users' => [99],
]
],
]));
如果运行上一个代码,它就变成了这个。
"users" => array:2 [
0 => 99
1 => 2
]
而不是期望的东西。
"users" => array:1 [
0 => 99
]
答案 0 :(得分:1)
编辑版本:
所以,我玩了一下,试图创建一个自定义函数来做你需要的。对我来说似乎有效。请试一试。如果我错过了什么,请告诉我。
基本上你从函数中删除了默认数组,然后为这个基数组添加一个变量。这允许函数调用自身并深入到数组中。
// removed base
$base = ['posts' => [
1 => [
'field1' => '',
'field2' => [],
'field3' => [],
'field4' => [],
'users' => [1, 2],
'field6' => '',
]
]];
// added base param
function validParams($base, $overrides) {
if(is_array($overrides)) {
// loop over override
foreach($overrides as $key => $overrideVal) {
// if override is an array such as base and there is a similar key in the base array,
// catch the base value as $baseVal. Then go one step down into base array
if (is_array($overrideVal) && (null!==($baseVal = isset($base[$key]) ? $base[$key] : null)) && is_array($baseVal)) {
// call self with baseval and override val
$base[$key] = validParams($baseVal,$overrideVal);
} else {
// no longer an array, here we will begin to overwrite
// loop trough known last base
foreach ($base as $baseKey => $basVal) {
// if the value is given in overwrite, then overwrite it
if ($baseKey == $key) {
$base[$key] = $overrideVal;
} else {
// was not given in overwrite, remove it
unset($base[$baseKey]);
}
}
}
}
}
return $base;
}
$result = validParams($base, [
'posts' => [
1 => [users => [99],
],
],
]);
var_dump($result);
抱歉,我将代码更改为程序样式,因为它更容易构建。