简体   繁体   English

在PHP中将2个数组合并为1个数组

[英]Merge 2 arrays into 1 array in PHP

I've 2 arrays:我有 2 个数组:

{"1":"red"}
{"1":"green","2":"red"}

It should remove 1 = green and replace it with 1 = red.它应该删除 1 = 绿色并将其替换为 1 = 红色。 Key 2 must simply remain.键 2 必须保持不变。

So, I want an array like this:所以,我想要一个这样的数组:

{"1":"red","2":"red"}

How can I do that in PHP?我怎样才能在 PHP 中做到这一点?

You could use the operator + :您可以使用运算符+

$a = [1 => "red"] ;
$b = [1 => "green", 2 => "red"] ;
print_r($a + $b) ;

Outputs :输出:

Array
(
    [1] => red
    [2] => red
)

From documentation :文档
The + operator returns the right-hand array appended to the left-hand array; + 运算符返回附加到左侧数组的右侧数组; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.对于同时存在于两个数组中的键,将使用左侧数组中的元素,而忽略右侧数组中的匹配元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM