array_merge
array_merge是很常用的数组合并函数,但是使用时可能会存在一些问题,开发时碰到了,记录一下
如下代码:
$arr = array();
$arr1 = array(
'100' => 'wmj100',
'101' => 'wmj101',
'102' => 'wmj102',
'103' => 'wmj103',
'104' => 'wmj104',
);
$arr2 = array(
'105' => 'wmj105',
'106' => 'wmj106',
'107' => 'wmj107',
'108' => 'wmj108',
'109' => 'wmj109',
);
$arr3 = array(
'110' => 'wmj110',
'111' => 'wmj111',
'112' => 'wmj112',
'113' => 'wmj113',
'114' => 'wmj114',
);
$arr = array_merge($arr1, $arr2, $arr3);
var_dump($arr);
以上代码会输出:
可以看出数组的键名已经被重置了,这有些时候是不符合我们的需求的,查阅手册:
如果是数字索引,array_merge后会重置索引从0开始变为一个新的索引数组。
------------------------------------------------------------------------------------------------------------------------
尝试关联数组:
<?php
$arr = array();
$arr1 = array(
'skr100'=>'wmj100',
'skr101'=>'wmj101',
'skr102'=>'wmj102',
'skr103'=>'wmj103',
'skr104'=>'wmj104',
);
$arr2 = array(
'skr105'=>'wmj105',
'skr106'=>'wmj106',
'skr107'=>'wmj107',
'skr108'=>'wmj108',
'skr109'=>'wmj109',
);
$arr3 = array(
'skr110'=>'wmj110',
'skr111'=>'wmj111',
'skr112'=>'wmj112',
'skr113'=>'wmj113',
'skr114'=>'wmj114',
);
$arr1 = array_merge($arr1,$arr2,$arr3);
var_dump($arr1);
查看结果,skr,发现键名都保留了
------------------------------------------------------------------------------------------------------------------
那么如果我们想要得到数字索引的合并结果应该如何做呢?查阅资料得知,php使用数组相加即可:
<?php
$arr1 = array(
'100'=>'wmj100',
'101'=>'wmj101',
'102'=>'wmj102',
'103'=>'wmj103',
'104'=>'wmj104',
);
$arr2 = array(
'105'=>'wmj105',
'106'=>'wmj106',
'107'=>'wmj107',
'108'=>'wmj108',
'109'=>'wmj109',
);
$arr3 = array(
'110'=>'wmj110',
'111'=>'wmj111',
'112'=>'wmj112',
'113'=>'wmj113',
'114'=>'wmj114',
);
$arr1 = $arr1+$arr2+$arr3;
var_dump($arr1);
执行结果:
因为php弱类型语言的缘故,所以即使使用字符串的数字键名,使用array_merge也会重置为索引数组,如果想要得到键名不被重置的合并结果,可以使用+,根据需求使用,切不可大意,对代码心存敬畏之心。