PHP根据键值合并数组

PHP根据键值合并数组

我们现在来分析一下在PHP开发过程中,如何合并两个数组,并且将相同键值的元素合并在一起。

示例1

最简单的合并方式

$a = [
   1=>'a',
   2=>'b',
   3=>'c'
];
$b = [
   3=>'e',
   4=>'f',
   5=>'c'
];
$c = $a+$b;
print_r($c);

输出:

Array ( [1] => a [2] => b [3] => c [4] => f [5] => c )

分析:$a[3]覆盖了$b[3],当数组存在相同键值的元素时,前面的数组将会后面相同键值的数组元素

示例2

用foreach循环赋值的方法

$a = [
   1=>'a',
   2=>'b',
   3=>'c'
];
$b = [
   3=>'e',
   4=>'f',
   5=>'a'
];
foreach ($b as $key => $val) {
   $a[$key] = $val;
}
print_r($a);

输出:

Array ( [1] => a [2] => b [3] => e [4] => f [5] => a )

分析:和示例1有点区别

用于做循环的数组$b将会覆盖数组$a的元素,而且只覆盖键值相同的元素

相关函数:

array_merge

array_intersect

array_intersect_ukey

array_intersect_uassoc

array_intersect_key

array_intersect_assoc

相关学习推荐:PHP编程从入门到精通

以上就是PHP根据键值合并数组的详细内容,更多请关注https://www.sxiaw.com/其它相关文章!