常用的合并数组的方法有三种:array_merge()、array_merge_recursive()、+,下面一个一个介绍
array_merge()
此函数合并一个或多个数组,当输入的数组中有相同的字符串键名,则后一个会覆盖前一个。对于参数数组中数字索引的值会重新排序,不管数字索引相同还是不同。
代码如下:
$arr1 = array(‘name‘ => ‘tom‘, 123, 456); $arr2 = array(‘age‘ => 13, ‘name‘ => ‘peter‘, ‘hello‘, ‘world‘); $arr = array_merge($arr1, $arr2); var_dump($arr1); var_dump($arr2); var_dump($arr);
运行结果:
array (size=3)
‘name‘ => string ‘tom‘ (length=3)
0 => int 123
1 => int 456
array (size=4)
‘age‘ => int 13
‘name‘ => string ‘peter‘ (length=5)
0 => string ‘hello‘ (length=5)
1 => string ‘world‘ (length=5)
array (size=6)
‘name‘ => string ‘peter‘ (length=5)
0 => int 123
1 => int 456
‘age‘ => int 13
2 => string ‘hello‘ (length=5)
3 => string ‘world‘ (length=5)
array_merge_recursive()
此函数会递归地合并一个或多个数组,当输入的数组中有相同的字符串键名时会合并到一个数组中,而不是覆盖。
代码如下:
$arr1 = array(‘name‘ => ‘tom‘, 123, 456); $arr2 = array(‘age‘ => 13, ‘name‘ => ‘peter‘, ‘hello‘, ‘world‘); $arr = array_merge_recursive($arr1, $arr2); var_dump($arr1); var_dump($arr2); var_dump($arr);
运行结果:
array (size=3)
‘name‘ => string ‘tom‘ (length=3)
0 => int 123
1 => int 456
array (size=4)
‘age‘ => int 13
‘name‘ => string ‘peter‘ (length=5)
0 => string ‘hello‘ (length=5)
1 => string ‘world‘ (length=5)
array (size=6)
‘name‘ =>
array (size=2)
0 => string ‘tom‘ (length=3)
1 => string ‘peter‘ (length=5)
0 => int 123
1 => int 456
‘age‘ => int 13
2 => string ‘hello‘ (length=5)
3 => string ‘world‘ (length=5)
+
加号在合并数组时如果出现数组中有相同的字符串键名或者是相同的数字索引时都会进行前边的值覆盖后边的值。
代码如下:
$arr1 = array(‘name‘ => ‘tom‘, 123, 456); $arr2 = array(‘age‘ => 13, ‘name‘ => ‘peter‘, ‘hello‘, ‘world‘); $arr = $arr1 + $arr2; var_dump($arr1); var_dump($arr2); var_dump($arr);
运行结果:
array (size=3)
‘name‘ => string ‘tom‘ (length=3)
0 => int 123
1 => int 456
array (size=4)
‘age‘ => int 13
‘name‘ => string ‘peter‘ (length=5)
0 => string ‘hello‘ (length=5)
1 => string ‘world‘ (length=5)
array (size=4)
‘name‘ => string ‘tom‘ (length=3)
0 => int 123
1 => int 456
‘age‘ => int 13
原文:https://www.cnblogs.com/wp1996/p/8992848.html