gpt4 book ai didi

php - 合并两个数组而不更改键值php

转载 作者:可可西里 更新时间:2023-11-01 12:45:00 24 4
gpt4 key购买 nike

我在 php 中有两个数组,如代码所示

<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>

我需要合并两个数组。 array_merge 函数成功合并了其中两个,但键值发生了变化。我需要以下输出

  Array
(
[0]=>Array(
[500] => 1
[502] => 2
[503] => 3
[504] => 5
)
)

我可以在 php 中使用什么函数,以便在不更改键值的情况下获得以下输出?

最佳答案

来自 the documentation , 示例 #3:

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}

因此,尝试:$a[0] + $b[0]

关于php - 合并两个数组而不更改键值php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18694076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com