【发布时间】:2014-09-12 03:38:25
【问题描述】:
我在 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,
)
);
现在我需要合并这些数组并保留空值,以便输出如下:
$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 的问题并在 Google 上搜索了很多,但我找到的答案不是递归的,或者只是不适用于这个问题。
编辑
正如上面解释为什么我问这个问题,即使我检查了其他问题的答案显然没有足够的证据或什么,我尝试了标记的重复问题答案,如下:
$merged = array_merge(array_filter($arr1, 'strval'), array_filter($arr2, 'strval'));
它给了一个数组到字符串的转换错误,因为它不是递归的,这就是我解释的。
【问题讨论】: