- $arr1=['1','2','3'];
- $arr2=['4',24,'6'];
- $all=array_combine($arr1, $arr2);//数组合并函数
- var_dump($all);
- php中数组的几种合并方法:
-
- array_merge(array1,array2):两个数组中的一维数据合并,二维数组如果key相同,array2中的值会替代array1中的值;
-
- 加号:array1+array2:把array2中key对应在array1不存在的key的值添加到array1中(像当于array1你有4个位置,则那4个位置的值不变,array2有5个位置,只把第5个位置的值加到array1中)
-
- array_merge_recursive:与array_merge唯一不同的是,二维数据的值不会替换,是递归合并到一起;
-
- $array1 = array(2,4,"color" => "red");
-
- $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
-
- $result = array_merge($array1, $array2);
-
- echo "----------------array_merge---------------".PHP_EOL;
-
- print_r($result);
-
- echo "----------------+++++++++++---------------".PHP_EOL;
-
- print_r($array1+$array2);
-
- echo "----------------array_merge_recursive---------------".PHP_EOL;
-
- print_r(array_merge_recursive($array1,$array2));
-
- ----------------array_merge---------------
-
- Array
-
- (
-
- [0] => 2
-
- [1] => 4
-
- [color] => green
-
- [2] => a
-
- [3] => b
-
- [shape] => trapezoid
-
- [4] => 4
-
- )
-
- ----------------+++++++++++---------------
-
- Array
-
- (
-
- [0] => 2
-
- [1] => 4
-
- [color] => red
-
- [shape] => trapezoid
-
- [2] => 4
-
- )
-
- ----------------array_merge_recursive---------------
-
- Array
-
- (
-
- [0] => 2
-
- [1] => 4
-
- [color] => Array
-
- (
-
- [0] => red
-
- [1] => green
-
- )
-
- [2] => a
-
- [3] => b
-
- [shape] => trapezoid
-
- [4] => 4
-
- )
-
- $array1 = array('a','b');
-
- $array2 = array(1,2);
-
- $result = array_merge($array1, $array2);
-
- echo "----------------array_merge---------------".PHP_EOL;
-
- print_r($result);
-
- echo "----------------+++++++++++---------------".PHP_EOL;
-
- print_r($array1+$array2);
-
- echo "----------------array_merge_recursive---------------".PHP_EOL;
-
- print_r(array_merge_recursive($array1,$array2));
-
- ----------------array_merge---------------
-
- Array
-
- (
-
- [0] => a
-
- [1] => b
-
- [2] => 1
-
- [3] => 2
-
- )
-
- ----------------+++++++++++---------------
-
- Array
-
- (
-
- [0] => a
-
- [1] => b
-
- )
-
- ----------------array_merge_recursive---------------
-
- Array
-
- (
-
- [0] => a
-
- [1] => b
-
- [2] => 1
-
- [3] => 2
-
- )