php中可以将两个或多个数组举办归并,生成一个归并后的新数组。这篇博文就讲一下关于PHP中归并数组的函数 array_merge()。
PHP array_merge() 函数array_merge():可以把两个或多个数组归并为一个新的数组。
语法:
array_merge(array1,array2,array3...)参数:
array1:要归并的数组1
array2:要归并的数组2
array3:要归并的数组3
例:PHP将两个数组归并成一个数组示例代码:
<?php $arr1 = array('上海','广州','杭州'); $arr2 = array('山东','北京','黑龙江'); print_r(array_merge($arr1,$arr2)); ?>打印功效:
Array ( [0] => 上海 [1] => 广州 [2] => 杭州 [3] => 山东 [4] => 北京 [5] => 黑龙江 )例:php多个数组归并示例代码:
<?php //飞鸟慕鱼博客 //http://www.feiniaomy.com $arr1 = array('shanghai','guanzhou','hangzhou'); $arr2 = array('shandong','beijing','heilongjiang'); $arr3 = array('xiamen','fujian','shanxi'); print_r(array_merge($arr1,$arr2,$arr3)); ?>打印功效:
Array ( [0] => shanghai [1] => guanzhou [2] => hangzhou [3] => shandong [4] => beijing [5] => heilongjiang [6] => xiamen [7] => fujian [8] => shanxi )例:PHP归并多个带有非数字键名的数组示例代码1:
<?php //飞鸟慕鱼博客 //http://www.feiniaomy.com $arr1 = array('a'=>'shanghai','b'=>'guanzhou','c'=>'hangzhou'); $arr2 = array('d'=>'shandong','e'=>'beijing','f'=>'heilongjiang'); print_r(array_merge($arr1,$arr2)); ?>打印功效:
Array ( [a] => shanghai [b] => guanzhou [c] => hangzhou [d] => shandong [e] => beijing [f] => heilongjiang )留意:两个含有非数字键名的数组归并后,新数组的各个元素的键名保持稳定。
示例代码2:
<?php //飞鸟慕鱼博客 //http://www.feiniaomy.com $arr1 = array('a'=>'aaaa','b'=>'bbbb','c'=>'cccc'); $arr2 = array('c'=>'dddd','e'=>'eeee','f'=>'ffff'); print_r(array_merge($arr1,$arr2)); ?>打印功效:
Array ( [a] => aaaa [b] => bbbb [c] => dddd [e] => eeee [f] => ffff )留意:假如多个要归并的数组中含有沟通元素的键名,则最后的元素会包围其他元素
例:php归并带有数字键名的数组代码1:
<?php //飞鸟慕鱼博客 //http://www.feiniaomy.com $arr1 = array(2=>'aaaa',1=>'bbbb',5=>'cccc'); $arr2 = array(4=>'dddd',6=>'eeee',7=>'ffff'); print_r(array_merge($arr1,$arr2)); ?>打印功效:
Array ( [0] => aaaa [1] => bbbb [2] => cccc [3] => dddd [4] => eeee [5] => ffff )代码2:
<?php //飞鸟慕鱼博客 //http://www.feiniaomy.com $arr1 = array(2=>'aaaa',1=>'bbbb',5=>'cccc'); print_r(array_merge($arr1)); ?>打印功效:
Array ( [0] => aaaa [1] => bbbb [2] => cccc )注:array_merge() 函数在处理惩罚带有数字键名的数组时,返回的新数组的键名都是数字,其键名以 0 开始举办从头索引