drmg17928 2014-04-04 09:46
浏览 97

使用array_merge函数合并两个数组时出现问题

I have two associative array.

$Array1 = array(
 'abc'=> 'abc',
 'def'=> 'def'
);

$Array2 = array(
 '123'=> '123',
 '456'=> '456'
);

I am merging them using array_merge.

$Array3 = array_merge($Array1, $Array2);

Now value of $Array3 is like this.

Array
(
    [abc] => abc
    [def] => def
    [0] => 123
    [1] => 456
)

It looks really odd until I read php manual which says Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. array_merge manual

My questing How can I merge both array without loosing their associative keys. Both array can have common KEYS and I don't want to loose my information also. :(

  • 写回答

3条回答

  • duancaozen6066 2014-04-04 09:48
    关注

    By +:

    $Array1 = array(
     'abc'=> 'abc',
     'def'=> 'def'
    );
    
    $Array2 = array(
     '123'=> '123',
     '456'=> '456'
    );
    var_dump($Array1 + $Array2);
    

    This will preserve the index, but note this will not overwrite the value of the first array if same key exists in first array.

    And if you want the overwrite working, then there is array_replace function for this:

    var_dump(array_replace($Array1, $Array2));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试