PHP array_merge问题

Isi*_*sis 1 php array-merge

$a = array('matches' => 
        array(
            '5' => array('weight' => 6),
            '15' => array('weight' => 6),
        )
    );

    $b = array('matches' => 
        array(
            '25' => array('weight' => 6),
            '35' => array('weight' => 6),
        )
    );

    $merge = array_merge($a, $b);

    print_r($merge);
Run Code Online (Sandbox Code Playgroud)

这个脚本的结果是

Array
(
    [matches] => Array
        (
            [25] => Array
                (
                    [weight] => 6
                )

            [35] => Array
                (
                    [weight] => 6
                )

        )

)
Run Code Online (Sandbox Code Playgroud)

但为什么?

我想结果是这样的:

Array
(
    [matches] => Array
        (
            [5] => Array
                (
                    [weight] => 6
                )

            [15] => Array
                (
                    [weight] => 6
                )
            [25] => Array
                (
                    [weight] => 6
                )

            [35] => Array
                (
                    [weight] => 6
                )

        )

) 
Run Code Online (Sandbox Code Playgroud)

Ste*_*hen 9

因为'matches'第一个数组中的键被第二个数组中的相同键覆盖.你需要这样做:

$merge = array('matches' => array());
$a = array(
    'matches' => array(
        '5' => array('weight' => 6),
        '15' => array('weight' => 6)
    )
);

$b = array(
    'matches' => array(
        '25' => array('weight' => 6),
        '35' => array('weight' => 6)
    )
);

$merge['matches'] = array_merge($a['matches'], $b['matches']);

print_r($merge);
Run Code Online (Sandbox Code Playgroud)

UPDATE

为了保留数字键,您必须这样做:

$merge['matches'] = $a['matches'] + $b['matches'];
Run Code Online (Sandbox Code Playgroud)

如果像这样使用数组union运算符,请记住以下来自php.net:

将保留第一个数组中的键.如果两个数组中都存在数组键,则将使用第一个数组中的元素,并忽略第二个数组中的匹配键元素.

http://php.net/manual/en/function.array-merge.php