1
$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);

这个脚本的结果是

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

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

        )

)

但为什么?

我想要的结果是这样的:

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

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

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

        )

) 
4

5 回答 5

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);

更新

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

$merge['matches'] = $a['matches'] + $b['matches'];

如果像这样使用数组联合运算符,只需记住 php.net 中的以下内容:

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

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

于 2010-10-25T21:30:25.310 回答
4

尝试使用array_merge_recursive而不是array_merge.

于 2010-10-25T21:31:47.823 回答
0

好吧,你可以手动完成:

    $mergedArray = array();    

    foreach($a as $key => $value)
    {
        $mergedArray[$key] = $value;
    }

    foreach($b as $key => $value)
    {
        $mergedArray[$key] = $value;
    }
于 2010-10-25T21:30:01.143 回答
0

您正在合并数组的顶层。该array_merge()函数看到它们都包含一个“匹配”元素,因此它选择一个作为合并结果。

如果你想让它扫描得更深,你需要在数组的下一层运行 array_merge()。在这种情况下,它相对简单,因为每个数组的顶层只有一个元素,所以你只需要一行 - 像这样:

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

不过,更复杂的数组结构需要更多的工作。

希望有帮助。

于 2010-10-25T21:30:15.123 回答
0

尝试:

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

您的问题是您正在将顶级 $a 数组与 $b 合并,并且这两个数组都有一个“匹配”索引,因此它接受了该元素的 $b 版本。您可以通过显式合并该索引的数组 ($a['matches'] 与 $b['matches']) 并将其分配给合并数组 ($merge['matches']) 来解决此问题,这将导致预期的行为。

或者array_merge_recursive会做你想做的事。

于 2010-10-25T21:31:35.187 回答