如何合并阵列和preserve钥匙? [英] How to merge array and preserve keys?

查看:101
本文介绍了如何合并阵列和preserve钥匙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);

我想将它们合并,并保持键和秩序,而不是重新索引!

I want to merge them and keep the keys and the order and not re-index!!

如何获得这样呢?

Array
(
    [a] => new value
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

我尝试array_merge(),但它不会是preserved键:

I try to array_merge() but it will not be preserved the keys:

print_r(array_merge($array1, $array2));

Array
(
    [a] => 'new value'
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [0] => 456
)

我尝试联合运营商,但它不会覆盖该元素:

I try to the union operator but it will not overwriting that element:

print_r($array1 + $array2);

Array
(
    [a] => 1   <-- not overwriting
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

我试着换地方,但顺序错了,不是我的需要:

I try to swapped place but the order is wrong, not my need:

print_r($array2 + $array1);

Array
(
    [d] => 4
    [e] => 5
    [f] => 6
    [a] => new value 
    [123] => 456
    [b] => 2
    [c] => 3
)

我不想使用一个循环,是有高性能?

I dont want to use a loop, is there a way for high performance?

推荐答案

您正在寻找 array_replace()

You're looking for array_replace():

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
print_r(array_replace($array1, $array2));

自PHP 5.3中提供的。

Available since PHP 5.3.

更新

您也可以使用union 数组运算符;它适用于旧版本实际上可能会更快太:

You can also use the union array operator; it works for older versions and might actually be faster too:

print_r($array2 + $array1);

这篇关于如何合并阵列和preserve钥匙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆