使用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个回答

Try this code :) it will work

    function my_merge($array1,$array2)
    {
       foreach($array2 as $key => $value)
       {
         $array1[$key] = $value;
       }
       return $array1;
    }

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

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

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

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));
dongnai2804
dongnai2804 array_replace_recursive()效果很好。 感谢帮助
6 年多之前 回复
douying6206
douying6206 两个数组都是多维的。 你的代码对我不起作用。
6 年多之前 回复
douduan9129
douduan9129 那么你期望的结果是什么,'common_key'=> array('value1','value2')?
6 年多之前 回复
duanqun7761
duanqun7761 两个阵列都可以有共同的密钥,我也不想丢失我的信息。 :(。我更新了这个问题。
6 年多之前 回复

For associative arrays, use

$result = $Array1 + $Array2;

-but note, that for numeric keys this will also re-index:

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

$Array2 = array(
 '123',
 '456'
);
var_dump($Array1 + $Array2);
//array(3) { [0]=> string(3) "abc" ["def"]=> string(3) "def" [1]=> string(3) "456" } 

If you have same keys in your arrays, you can use:

$result = array_reduce(array_keys($Array1), function($c, $x) use ($Array1)
{
    $c[$x] = isset($c[$x])
       ?array_merge((array)$c[$x], [$Array1[$x]])
       :$Array1[$x];
    return $c;
}, $Array2);
dongmu3187
dongmu3187 嗯,我已经更新了(所以在这种情况下你会有这些键的值数组)
6 年多之前 回复
douxian6694
douxian6694 两个阵列都可以有共同的密钥,我也不想丢失我的信息。 :(。我更新了这个问题。
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问