如何合并数组并保留键? [英] How to merge array and preserve keys?

查看:23
本文介绍了如何合并数组并保留键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

$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() 但它不会保留密钥:

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
)

我不想使用循环,有没有高性能的方法?

推荐答案

您正在寻找 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.

更新

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

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

print_r($array2 + $array1);

这篇关于如何合并数组并保留键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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