本文介绍了PHP array_merge与数字键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让这么array_merge()会覆盖不同的值,但同一个密钥索引两键来自两个阵列?

How can make it so array_merge() overwrites two keys with different values but same key index from two arrays?

例如,合并:

[0] => 无论'

[0] => 什么,[1] => 一个,[2] => 'B'

应该产生

[0] => 什么,[1] => 一个,[2] => 'B'

基本上我想array_merge到bahave如果阵列具有字符串键它的行为同样的方式...

Basically I want array_merge to bahave the same way it behaves if the arrays have string keys...

推荐答案

使用 + 运营商。

比较 array_merge + 运营商:

<?php

$a1 = array(0=>"whatever",);
$a2 = array(0=>"whatever",1=>"a",2=>"b");

print_r(array_merge($a1,$a2));
print_r($a1+$a2);
?>

输出:

Array
(
    [0] => whatever
    [1] => whatever
    [2] => a
    [3] => b
)
Array
(
    [0] => whatever
    [1] => a
    [2] => b
)

+ 操作符的还是工作,如果你的关联数组具有数字键外的顺序为:

The + operator still works if your associative array has the numerical keys out-of-order:

<?php

$a1 = array(0=>"whatever",);
$a2 = array(1=>"a",0=>"whatever",2=>"b");

print_r(array_merge($a1,$a2));
print_r($a1+$a2);
?>

输出:

Array
(
    [0] => whatever
    [1] => a
    [2] => whatever
    [3] => b
)
Array
(
    [0] => whatever
    [1] => a
    [2] => b
)

通知 array_merge 这个的情况下创建一个新的密钥。不可取的......

Notice array_merge in this case creates a new key. Not desirable...

这篇关于PHP array_merge与数字键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 10:15