【发布时间】:2014-03-31 03:12:05
【问题描述】:
我有两个数组,第一个是我从函数中得到的结果,第二个包含默认值。我想用第二个数组中的值替换第一个数组中的空值。
$result = [
'NOTNULL',
null,
null,
null,
null
];
$defaults = [
'default1',
'default2',
[
null,
null,
null
]
];
# transforming $result array (to have the same form as $defaults array)
array_splice($result, 2, 3, [array_slice($result, 2)]);
$result = array_replace_recursive(
$default,
$result
);
输出:
Array (
[0] => NOTNULL
[1] => null
[2] => Array (
[0] => Array ()
[1] => null
[2] => null
)
)
预期:
Array (
[0] => NOTNULL
[1] => default2
[2] => Array (
[0] => null
[1] => null
[2] => null
)
);
我知道我得到了这个结果,因为array_replace_recursive 将传递数组中的元素递归地替换到第一个数组中,但是我怎样才能只更改非空值?
也许我应该这样做?
$result[0] = (array_key_exists(0, $result) || $result[0] === null) ? $defaults[0] : $result[0];
... 对于数组中的每个键?我想保留两个数组中为空的空值。目前这是我找到的唯一解决方案,但它不是很优雅......
我怎样才能得到预期的结果?我没有任何想法。
【问题讨论】:
-
你为什么从那个函数返回空值?如果您知道要进行数组比较,使用 array_push 不是更有意义吗?
-
你应该再次重构你的函数(登录)
-
@iamthereplicant 因为我的 $result 数组必须和
$defaults的形式相同,空值更容易拼接。array_push在数组末尾添加一个元素,不是吗?我会试试的。