考虑两个简单的数组:
<?php
$array1 = array(
'blue' => 5,
'green' => array(
'square' => 10,
'sphere' => 0.5,
'triangle' => 3
),
'red' => array(
'circle' => 1000,
),
'black' => 4,
);
$array2 = array(
'blue' => 1,
'green' => array(
'square' => 11,
'circle' => 5,
),
'purple' => 10,
'yellow' => array(
'triangle' => 4
),
'black' => array(
'circle' => 6,
),
);
我需要以递归的方式将每个和的每个值在数学上相加。$array1
$array2
- 保留密钥
- 如果键不存在
$array1
但确实存在于 中$array2
,则最终数组将仅包含 的值$array2
(反之亦然) - 如果两者都存在,则将添加数值
+
- 不会触及非数字值
- 如果 on 上的值
$array1
指向另一个子数组,并且在$array2
其中指向一个值,则最终值将导致该键包含一个子数组,该子数组包含来自的值$array1
以及使用父名称及其值的新键/值(请参阅black
在示例中) - 应该能够以几乎无限的嵌套工作
澄清一下,例如,如果我们说
<?php
$final = array_merge_special($array1, $array2);
// We would end up with, if you var_export()'d final, something like:
// (Note: Hope I didn't make mistakes in this or it will be confusing,
// so expect mild human error)
$final = array(
'blue' => 6, // 5+1
'green' => array(
'square' => 21, // (10+11)
'sphere' => 0.5, // only in $array1
'triangle' => 3 // only in $array1
'circle' => 5, // only in $array2
),
'purple' => 10, // only in $array2
'yellow' => array( // only in $array2
'triangle' => 4
),
'red' => array( // only in $array1
'circle' => 1000,
),
'black' => array(
'circle' => 6, // untouched, while $black is present in both, the $array1 value does not have a 'circle' key, and is actually only a key/value (see below)
'black' => 4, // the key/value from $array1 that was not a subarray, even though it was a subarray in $array2
),
);
这对我来说似乎令人生畏。我知道我可以遍历一个数组并轻松地递归地添加值,并且我有这个工作(有点),但是当我进入特殊规则(例如 for 的规则black
)时,我什至无法想象代码会如何损坏看。必须有一种方法可以单独循环每个数组并将unset()
值合并?