我正在尝试获取两个数组,并将它们相互合并。第一个数组用作"索引"数组,即 - 这是输出数组理想的格式:
$array1 = [
'DIV1' => 'Some element data',
'SUPPLEMENTAL' => [
'RPC' => '10.24.122.32',
'PORT' => '8080'
],
'ASG' => 'some arbitrary data'
];
$array2 = [
'DIV2' => 'Some more element data',
'ASG' => 'different arbitrary data',
'DIV1' => 'Some element data that refers to the other object'
'SUPPLEMENTAL' => [
'RPC' => '10.24.123.1'
]
];
因此,在合并之后,我们将有效地拥有两个数组。这可以作为调用两次的单个函数来完成,该函数将每个数组作为参数传递(第二次调用时反向 - 并以某种方式定义索引数组(。键将仅沿用,没有值。我们最终会得到如下所示的数组:
$array1 = [
'DIV1' => 'Some element data',
'DIV2' => '', // blank because only key was moved
'SUPPLEMENTAL' => [
'RPC' => '10.24.122.32',
'PORT' => '8080'
],
'ASG' => 'some arbitrary data'
];
$array2 = [
'DIV1' => 'Some element data that refers to the other object'
'DIV2' => 'Some more element data',
'SUPPLEMENTAL' => [
'RPC' => '10.24.123.1',
'PORT' => '' // blank because only key was moved
],
'ASG' => 'different arbitrary data'
];
导入的(空白(键按某种顺序放置并不是非常重要,但保留现有元素的顺序很重要。只要它遵守索引数组的顺序定义(在本例中为 array1(。
我想我需要对多个维度进行某种嵌套排序。
由于您的数据没有相同顺序的键,因此很难保持键顺序,但您可以使用递归函数实现所需的目标:
function recursiveReKeyArrays(array $array1, array $array2)
{
// Loop through the array for recursion
foreach ($array2 as $key => $value) {
if (!is_array($value)) {
continue;
}
$array1[$key] = recursiveReKeyArrays($array1[$key], $value);
}
// Find the differences in the keys
foreach (array_diff_key($array2, $array1) as $key => $value) {
$array1[$key] = null;
}
return $array1;
}
这将遍历第二个数组,找到任何数组值并递归到它们中,找到任何丢失的键并将它们设置为 null
。
这将为您提供以下输出:
Array
(
[DIV1] => Some element data
[SUPPLEMENTAL] => Array
(
[RPC] => 10.24.122.32
[PORT] => 8080
)
[ASG] => some arbitrary data
[DIV2] =>
)
Array
(
[DIV2] => Some more element data
[ASG] => different arbitrary data
[DIV1] => Some element data that refers to the other object
[SUPPLEMENTAL] => Array
(
[RPC] => 10.24.123.1
[PORT] =>
)
)
此处的示例:http://ideone.com/5ml1y4