dsa5211314
dsa5211314
2012-03-25 19:02

为什么array_merge_recursive像这样工作?

已采纳

I have 3 arrays like this:

1st

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

2nd

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

3rd

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

array_merge_recursive(array1,array2,array3) produces:

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

but if the array keys are like this

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] => ''
                        )
                )
        )
)

this produce result like this

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

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

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

Any idea why this happening and how to prevent this and get the result as first one?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drpkcwwav20524605 drpkcwwav20524605 9年前

    From the documentation:

    If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

    "0695" is not a numeric key, but "1685" is.

    The first comment (in fact most of the comments) on that page describes a workaround.

    点赞 评论 复制链接分享