这期内容当中小编将会给大家带来有关怎么在php中实现数组合并,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
成都创新互联IDC提供业务:成都服务器托管,成都服务器租用,成都服务器托管,重庆服务器租用等四川省内主机托管与主机租用业务;数据中心含:双线机房,BGP机房,电信机房,移动机房,联通机房。
直接将两个数组的值合并成为一个数组;
$a = [1,2,3,'a'=>'a']; $b = ['a'=>'b',4,5,'b'=>'c',6,7,'a']; $c = $a + $b; print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [1] => 2 [2] => 3 [a] => a ) //$b Array ( [a] => b [0] => 4 [1] => 5 [b] => c [2] => 6 [3] => 7 [4] => a ) //$c Array ( [0] => 1 [1] => 2 [2] => 3 [a] => a [b] => c [3] => 7 [4] => a )
采用"+"合并数组,如果键相同的情况下,前面的数组值会覆盖掉后面的数组值。
将某个变量放入到另一个数组当中
$a = [1,'a'=>'aa',2,'b'=>'bb']; $b = [1,'a'=>'aa',2,'b'=>'bb']; print_r($a); print_r($b); array_push($a, $b); print_r($a); //$a Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) //$b Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) // array_push过后的$a Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb [2] => Array ( [0] => 1 [a] => aa [1] => 2 [b] => bb ) )
通过打印的值可以看出,变量进入数组后,对应的数字索引必然是当前数组中最小的数字索引+1(如果当前数组不存在数字索引,新增元素对应的索引为0)
直接将两个数组进行合并,两个数组键相同的情况,后面数组的值覆盖前面数组的值
$a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'c','b'=>'d','c'=>'e']; $c = array_merge($a,$b); print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [2] => 2 [a] => a [b] => b ) //$b Array ( [0] => 1 [2] => 3 [a] => c [b] => d [c] => e ) //$c Array ( [0] => 1 [1] => 2 [a] => c [b] => d [2] => 1 [3] => 3 [c] => e )
可以看出,两个数组键相同的情况,后面数组的值覆盖前面数组的值。但是对于数字索引或者数字字符串索引,会按照顺序进行重置(第一个数组的第一个数字索引元素从0开始依次填充)
合并数组,遇到相同的键将该键中值合并为一个子数组
$a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'a','b'=>'d','c'=>'e']; $c = array_merge_recursive($a,$b); print_r($a); print_r($b); print_r($c); //$a Array ( [0] => 1 [2] => 2 [a] => a [b] => b ) //$b Array ( [0] => 1 [2] => 3 [a] => a [b] => d [c] => e ) //$c Array ( [0] => 1 [1] => 2 [a] => Array ( [0] => a [1] => a ) [b] => Array ( [0] => b [1] => d ) [2] => 1 [3] => 3 [c] => e )
上述就是小编为大家分享的怎么在php中实现数组合并了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。