带数字键的 PHP array_merge

2022-08-30 10:42:13

如何使它如此array_merge()覆盖两个数组中具有不同值但相同键索引的两个键?

例如,合并:

[0] => 'whatever'

[0] => 'whatever', [1] => 'a', [2] => 'b'

应该产生

[0] => 'whatever', [1] => 'a', [2] => 'b'

基本上,我希望array_merge以与数组具有字符串键时相同的行为方式进行bahave...


答案 1

使用运算符。+

与运算符比较:array_merge+

<?php

$a1 = array(0=>"whatever",);
$a2 = array(0=>"whatever",1=>"a",2=>"b");

print_r(array_merge($a1,$a2));
print_r($a1+$a2);
?>

输出:

Array
(
    [0] => whatever
    [1] => whatever
    [2] => a
    [3] => b
)
Array
(
    [0] => whatever
    [1] => a
    [2] => b
)

如果关联数组的数字键无序,则运算符仍然有效:+

<?php

$a1 = array(0=>"whatever",);
$a2 = array(1=>"a",0=>"whatever",2=>"b");

print_r(array_merge($a1,$a2));
print_r($a1+$a2);
?>

输出:

Array
(
    [0] => whatever
    [1] => a
    [2] => whatever
    [3] => b
)
Array
(
    [0] => whatever
    [1] => a
    [2] => b
)

请注意,在这种情况下,将创建一个新密钥。不可取...array_merge


答案 2

array_replace正是这样做的!