合并两个数组

Awa*_*wan 77 php arrays unique

我有两个像这样的数组:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
Run Code Online (Sandbox Code Playgroud)

我想组合这两个数组,使它不包含重复,并保留其原始键.例如输出应该是:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它正在更改原来的密钥:

$output = array_unique( array_merge( $array1 , $array2 ) );
Run Code Online (Sandbox Code Playgroud)

有解决方案吗

Kin*_*nch 147

只需使用:

$output = array_merge($array1, $array2);
Run Code Online (Sandbox Code Playgroud)

那应该解决它.因为如果一个键出现多次(例如'44'在您的示例中),则使用字符串键,一个键将覆盖具有相同名称的过程键.因为在你的情况下,它们都具有相同的值,无论如何它都无关紧要,它也将删除重复.

更新:我刚刚意识到,PHP将数字字符串键视为数字(整数),所以表现得像这样,这意味着,它也重新编号键...

解决方法是重新创建密钥.

$output = array_combine($output, $output);
Run Code Online (Sandbox Code Playgroud)

更新2:我总是忘记,还有一个操作员(粗体,因为这是你真正想要的!:D)

$output = $array1 + $array2;
Run Code Online (Sandbox Code Playgroud)

  • @KingCrunch - 即使引用了数字,这些也不是**字符串键,因此不会保留索引**.示例:https://ideone.com/I2NFT (5认同)
  • 所以`$ array1 + $ array2`是简短有效的解决方案,而不是`array_merge() - array_combine()`组合 (3认同)
  • 警告!对于非关联数组或者如果数组有公共键 `$a + $b != array_merge($a, $b)` (3认同)

ine*_*nja 31

你应该考虑到这一点 $array1 + $array2 != $array2 + $array1

$array1 = array(
'11' => 'x1',
'22' => 'x1' 
);  

$array2 = array(
'22' => 'x2',
'33' => 'x2' 
);
Run Code Online (Sandbox Code Playgroud)

使用$ array1 + $ array2

$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
Run Code Online (Sandbox Code Playgroud)

$ array2 + $ array1

$array2 + $array1 = array(  
'11' => 'x1',  
'22' => 'x2',  
'33' => 'x2'  
);
Run Code Online (Sandbox Code Playgroud)


Mic*_*has 24

这有效:

$output = $array1 + $array2;
Run Code Online (Sandbox Code Playgroud)

  • 我不推荐这个,因为它的行为是非常不直观的,例如`[1,2,3] + [4,5,6] == [1,2,3]` (9认同)

Sho*_*med 11

使用php7.4执行此操作的新方法是 Spread 运算符[...]

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Run Code Online (Sandbox Code Playgroud)

扩展运算符应该具有比array_merge

Spread 运算符的一个显着优点是它支持任何可遍历的对象,而 array_merge 函数仅支持数组。