在 PHP 中将 2 个数组合并为 1 个数组
Merge 2 arrays into 1 array in PHP
我有 2 个数组:
{"1":"red"}
{"1":"green","2":"red"}
它应该删除 1 = 绿色并替换为 1 = 红色。键 2 必须保留。
所以,我想要一个这样的数组:
{"1":"red","2":"red"}
我如何在 PHP 中做到这一点?
您可以使用运算符 +
:
$a = [1 => "red"] ;
$b = [1 => "green", 2 => "red"] ;
print_r($a + $b) ;
输出:
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.
我有 2 个数组:
{"1":"red"}
{"1":"green","2":"red"}
它应该删除 1 = 绿色并替换为 1 = 红色。键 2 必须保留。
所以,我想要一个这样的数组:
{"1":"red","2":"red"}
我如何在 PHP 中做到这一点?
您可以使用运算符 +
:
$a = [1 => "red"] ;
$b = [1 => "green", 2 => "red"] ;
print_r($a + $b) ;
输出:
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.