[英]array_merge() without losing null values
我在PHP中有2个数组,一个数组模拟可以编辑的属性,另一个数组包含属性和它应具有的值。
示例如下:
$arr1 = array(
'entity1' => array(
'property1' => null,
'property2' => null,
),
'entity2' => array(
'property3' => null,
'property4' => null,
'property5' => null,
)
);
$arr2 = array(
'entity1' => array(
'property1' => 1,
'property2' => 0,
),
'entity2' => array(
'property3' => 0,
'property4' => 1,
)
);
现在,我需要合并这些数组并保留null值,以便输出如下:
$output = array(
'entity1' => array(
'property1' => 1,
'property2' => 0,
),
'entity2' => array(
'property3' => 0,
'property4' => 1,
'property5' => null,
)
);
我尝试了array_merge()
和$arr1 + $arr2
都输出:
Array
(
[entity1] => Array
(
[property1] => 1
[property2] => 0
)
[entity2] => Array
(
[property3] => 0
[property4] => 1
)
)
数组可以比示例中显示的要深,因此它必须是递归的,并且数组都是关联的。
我已经在StackOverflow和Googled上阅读了很多问题,但是我发现的答案不是递归的,或者不适用于该问题。
编辑
正如以上关于为什么我问了这个问题(尽管我用答案检查了其他问题显然不足以证明)之类的解释,我尝试了标记重复问题的答案,如下所示:
$merged = array_merge(array_filter($arr1, 'strval'), array_filter($arr2, 'strval'));
它给数组一个字符串转换错误的原因是它不是递归的,这就是我所解释的。
此递归函数可能是一个起点:
function merge_associative($arr1, $arr2) {
$merged = $arr1;
foreach ($arr2 as $k => $v) {
if (is_array($v) && is_array($arr1[$k]))
$merged[$k] = merge_associative($arr1[$k], $v);
else
$merged[$k] = $v;
}
return $merged;
}
它将合并关联数组,但不能正确处理数字索引。
function array_join() {
$args = func_get_args();
if (count($args) == 1 && isset($args[0], $args[1])) {
foreach ($args[0] as $value) {
$param[] = $value;
}
}else{
$param = $args;
}
$array = merge_associative($param[0], $param[1]);
unset($param[0]);
unset($param[1]);
if (isset($param[2])) $array = array_join($array, $param[2]);
return $array;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.