is it possible to merge 2 arrays without overlapping the same keys ?
是否可以合并两个数组而不重叠相同的键?
I want it to add a new item if a key already exists.
如果键已经存在,我希望它添加一个新项。
Like that
像这样
$a = array(1,2,3,4);
$b = array(3,4,5,6);
merge $a and $b
desired result is
预期的结果是
array(1,2,3,4,3,4,5,6)
4 个解决方案
#1
0
Use array_merge
使用array_merge
$a = array(1,2,3,4);
$b = array(3,4,5,6);
$c = array_merge($a,$b);
print_r($c);
工作的例子
This is the key phrase from the help :
这是来自帮助的关键短语:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
如果输入数组具有相同的字符串键,那么该键的后一个值将覆盖前一个键。但是,如果数组包含数字键,则后面的值将不会覆盖原始值,而是将被追加。
So this will only work when you have numeric keys
只有当你有数字键的时候,这个才有效
#3
0
You can use the function array_merge
for this purpose. But I want to point out that the contents of the arrays are the values of the arrays and not keys. In PHP you cannot have duplicate keys.
为此,您可以使用函数array_merge。但我想指出的是,数组的内容是数组的值,而不是键。在PHP中,不能有重复的键。
#4
0
Try
试一试
<?php
$merged_array = array_merge($a, $b);
?>
Also exists function array_merge_recursive.
也存在array_merge_recursive函数。
#1
0
Use array_merge
使用array_merge
$a = array(1,2,3,4);
$b = array(3,4,5,6);
$c = array_merge($a,$b);
print_r($c);
工作的例子
This is the key phrase from the help :
这是来自帮助的关键短语:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
如果输入数组具有相同的字符串键,那么该键的后一个值将覆盖前一个键。但是,如果数组包含数字键,则后面的值将不会覆盖原始值,而是将被追加。
So this will only work when you have numeric keys
只有当你有数字键的时候,这个才有效
#2
#3
0
You can use the function array_merge
for this purpose. But I want to point out that the contents of the arrays are the values of the arrays and not keys. In PHP you cannot have duplicate keys.
为此,您可以使用函数array_merge。但我想指出的是,数组的内容是数组的值,而不是键。在PHP中,不能有重复的键。
#4
0
Try
试一试
<?php
$merged_array = array_merge($a, $b);
?>
Also exists function array_merge_recursive.
也存在array_merge_recursive函数。