为什么array_merge_recursive像这样工作?

时间:2012-03-25 19:02:29

标签: php array-merge

我有3个这样的数组:

第一

Array
(
    [0695] => Array
        (
            [loan_number] => 0695
            [start_date] => 2011-12-25
        )
)

第二

Array
(
    [0695] => Array
        (
            [name] => ''
            [address] => ''
        )
)

第三

Array
(
    [0695] => Array
        (
            [items] => Array
                (
                    [0] => Array
                        (
                            [item] => ''
                            [qty] => ''
                            [price] => ''
                        )
                )
        )
)

array_merge_recursive(array1,array2,array3)产生:

Array
(
    [0695] => Array
        (
            [loan_number] => 0695
            [start_date] => 2011-12-25
            [name] => ''
            [address] => ''
            [items] => Array
                (
                    [0] => Array
                        (
                            [item] => ''
                            [qty] => ''
                            [price] => ''
                        )
                )
        )
)

但如果数组键是这样的

Array
(
    [1685] => Array
        (
            [loan_number] => 1685
            [start_date] => 2011-12-25
        )
)

Array
(
    [1685] => Array
        (
            [name] => ''
            [address] => ''
        )
)

Array
(
    [1685] => Array
        (
            [items] => Array
                (
                    [0] => Array
                        (
                            [item] => ''
                            [qty] => ''
                            [price] => ''
                        )
                )
        )
)

这会产生这样的结果

Array
(
    [0] => Array
        (
            [loan_number] => 1685
            [start_date] => 2011-12-25
        )

    [1] => Array
        (
            [name] => ''
            [address] => ''
        )

    [2] => Array
        (
            [items] => Array
                (
                    [0] => Array
                        (
                            [item] => ''
                            [qty] => ''
                            [price] => ''
                        )
                )
        )
)

知道为什么会发生这种情况以及如何防止这种情况并将结果作为第一个结果?

1 个答案:

答案 0 :(得分:2)

来自documentation

  

但是,如果数组具有相同的数字键,则后面的值不会覆盖原始值,但会被追加。

“0695”不是数字键,但“1685”是。

该页面上的first comment(实际上是大多数评论)描述了一种解决方法。