我有两个要以递归方式合并的数组,因此添加数组不是一个选项。这是一个简单的例子,没有多级别来证明这个问题:
$a1 = Array(
5 => 'pronoun'
)
$a2 = Array(
2 => 'verb',
3 => 'noun'
)
$r = array_merge_recursive($a1, $a2)
我想得到那个结果数组:
Array(
5 => 'pronoun'
2 => 'verb',
3 => 'noun'
)
我的问题是array_merge_recursive
函数重新加入了键,我得到以下内容:
Array(
0 => 'pronoun'
1 => 'verb',
2 => 'noun'
)
我理解这种情况正在发生,因为我的所有按键都是数字的。所以我在添加时尝试将它们设为字符串,但它似乎没有正常工作:
$a1[(string)7] = 'some value';
键 - 7 - 仍然是数字,或者至少是它在调试器中显示的方式 - $a1[7]
而不是$a1['7']
。有什么建议吗?
编辑: 添加数组不是一种选择。请看为什么。我有两个多级数组:
$a1 = array (
1 => array (
1 => "man1",
2 => "man"
),
2 => array (
1 => "run",
2 => "nice"
)
);
$a2 = array(
2 => array (
1 => "to observe",
2 => "to examine visually"),
3 => array(
1 => "look nice",
2 => "appear, seem to be"));
$r = $a1 + $a2;
我期望以下内容:
$r = Array(
...
2 => array(
1 => array("run", "to observe")
2 => array("nice", "to examine visually")
));
但是不添加第二个数组中键2的选项:
$r = Array(
...
2 => array(
1 => "run",
2 => "nice"
));
答案 0 :(得分:3)
您只需使用$a1+$a2
即可获得结果
$a1 = array(
5 => 'pronoun'
);
$a2 = array(
2 => 'verb',
3 => 'noun'
);
print_r($a1+$a2);
用于递归数组
$a1 = array(
5 => 'pronoun'
);
$a2 = array(array('a', 'z'), array(2 => 'p', 'q'));
print_r($a1+$a2);
结果是
Array
(
[5] => pronoun
[0] => Array
(
[0] => a
[1] => z
)
[1] => Array
(
[2] => p
[3] => q
)
)
这是你想要实现的目标吗?
答案 1 :(得分:2)
这应该适用于您的特定问题:
function assoc_merge(array $a, array $b)
{
$r = array();
foreach ($a as $key => $val) {
if (array_key_exists($key, $b) && is_array($val) == is_array($b[$key])) {
if (is_array($val)) {
$r[$key] = assoc_merge($a[$key], $b[$key]); // merge array
} else {
$r[$key] = array($val, $b[$key]); // merge entry
}
} else {
$r[$key] = $val; // just copy
}
}
return $r + $b; // add whatever we missed
}
print_r(assoc_merge($a1, $a2));
答案 2 :(得分:1)
您可以随时尝试手动案例。
function merge () { // takes any number of arguments
$arrays = func_get_args();
$result = array();
foreach ($arrays as $array)
foreach ($array as $key => $item)
if (is_array($item))
$result = merge($result, $item);
else
$result[$key] = $item;
return $result;
当然,它很慢,但它会起作用。
答案 3 :(得分:1)
$a1 = array(
5 => 'pronoun'
);
$a2 = array(
2 => 'verb',
3 => 'noun'
);
foreach($a2 as $key=>$value) {
$a1[$key] = $value;
}
print_r($a1);
答案 4 :(得分:1)
<?php
$a = [ 5 => 'pronoun'];
$b = [ 2 => 'verb', 3 => 'noun'];
$m = array_merge(array_keys($a), array_keys($b));
$final = array_combine($m, array_merge_recursive($a, $b));
print_r($final);