php数组合并
1、array_merge() 函数把一个或多个数组合并为一个数组。
提示:您可以向函数输入一个或者多个数组。
代码如下:
array_merge(array1,array2,array3...)
$dataFirst=array("first","second");
$dataSecond=array("third","fourth");
print_r(array_merge($dataFirst,$dataSecond));
返回:Array (
[0] => first
[1] => second
[2] => third
[3] => fourth
)
如果两个或更多个数组元素有相同的键名,则最后的元素会覆盖其他元素
$dataFirst=array("a"=>"first","b"=>"second");
$dataSecond=array("c"=>"third","b"=>"fourth");
print_r(array_merge($dataFirst,$dataSecond));
返回:Array (
[a] => first
[b] => fourth
[c] => third
)
2、array_merge_recursive() 函数把一个或多个数组合并为一个数组。
该函数与 array_merge() 函数的区别:
数组中有相同的键名时,array_merge_recursive() 不会进行键名覆盖,而是将多个相同键名的值递归组成一个数组。
$dataFirst=array("a"=>"first","b"=>"second");
$dataSecond=array("c"=>"third","b"=>"fourth");
print_r(array_merge_recursive($dataFirst,$dataSecond));
返回:Array (
[a] => first
[b] => Array (
[0] => second
[1] => fourth
)
[c] => third
)
3、array_combine() 通过合并两个数组来创建一个新数组,其中的一个数组是键名,另一个数组的值为键值
提示:如果其中一个数组为空,或者两个数组的元素个数不同,则该函数返回 false
$dataFirst=array("first","second");
$dataSecond=array("third","fourth");
print_r(array_combine($dataFirst,$dataSecond));
返回:Array (
[first] => third
[second] => fourth
)

浙公网安备 33010602011771号