doutuo1908 2012-12-28 13:22
浏览 10
已采纳

如何防止重新编号assoc_merge的结果?

I use array_merge function for merging two arrays. In most case it works properly

$x = array_merge(array('a' => 'x', 'b' => 'x'), array('b' => 'y', 'c' => 'y'));
var_dump($x);

// array(3) { ["a"]=> string(1) "x" ["b"]=> string(1) "y" ["c"]=> string(1) "y" }

But for numeric case it returns unexpected result

$x = array_merge(array('1' => 'x', '2' => 'x'), array('2' => 'y', '3' => 'y'));
var_dump($x);

// array(4) { [0]=> string(1) "x" [1]=> string(1) "x" [2]=> string(1) "y" [3]=> string(1) "y" }

How to prevent renumbering of indexes? There is way to merge two arrays by base php functions without renumbering of numeric indexes?

  • 写回答

3条回答 默认 最新

  • dream2891 2012-12-28 13:28
    关注

    from the manual:

    If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

    so, instead use array_replace.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?