作者:拍友2502921323 | 来源:互联网 | 2014-06-17 17:22
合并数据在php中我们利用array_merge()函数来实现,array_merge()函数把两个或多个数组合并为一个数组。如果键名有重复,该键的键值为最后一个键名对应的值(后面的覆盖前面的)。
合并数据在php中我们利用array_merge()函数来实现,array_merge() 函数把两个或多个数组合并为一个数组. 如果键名有重复,该键的键值为最后一个键名对应的值(后面的覆盖前面的).如果数组是数字索引的,则键名会以连续方式重新索引.
实例代码如下:
- echo "rn第一种情况rn";
- $a=array(1,2,3,4,5,6);
- $b=array(7,8,9);
-
- $c=array_merge ($a,$b);
- print_r($c);
- $c=$a+$b;
- print_r($c);
- $c=$b+$a;
- print_r($c);
-
-
- echo "rn第二种情况rn";
- $a=array('a','b','c','d','e','f');
- $b=array('a','x','y');
-
- $c=array_merge ($a,$b);
- print_r($c);
- $c=$a+$b;
- print_r($c);
- $c=$b+$a;
- print_r($c);
-
-
- echo "rn第三种情况rn";
-
- $a=array(
- 1=>'a',
- 2=>'b',
- 3=>'c',
- 4=>'d',
- 5=>'e',
- 6=>'f');
- $b=array(
- 1=>'a',
- 7=>'x',
- 8=>'y');
-
- $c=array_merge ($a,$b);
- print_r($c);
- $c=$a+$b;
- print_r($c);
- $c=$b+$a;
- print_r($c);
- ?>
- 结果如下:
- 第一种情况
- Array
- (
- [0] => 1
- [1] => 2
- [2] => 3
- [3] => 4
- [4] => 5
- [5] => 6
- [6] => 7
- [7] => 8
- [8] => 9
- )
- Array
- (
- [0] => 1
- [1] => 2
- [2] => 3
- [3] => 4
- [4] => 5
- [5] => 6
- )
- Array
- (
- [0] => 7
- [1] => 8
- [2] => 9
- [3] => 4
- [4] => 5
- [5] => 6
- )
-
- 第二种情况
- Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- [4] => e
- [5] => f
- [6] => a
- [7] => x
- [8] => y
- )
- Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- [4] => e
- [5] => f
- )
- Array
- (
- [0] => a
- [1] => x
- [2] => y
- [3] => d
- [4] => e
- [5] => f
- )
-
- 第三种情况
- Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- [4] => e
- [5] => f
- [6] => a
- [7] => x
- [8] => y
- )
- Array
- (
- [1] => a
- [2] => b
- [3] => c
- [4] => d
- [5] => e
- [6] => f
- [7] => x
- [8] => y
- )
- Array
- (
- [1] => a
- [7] => x
- [8] => y
- [2] => b
- [3] => c
- [4] => d
- [5] => e
- [6] => f
- )
1)键名为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)
2)键名为字符时,+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值
注释:如果仅仅向 array_merge() 函数输入了一个数组,且键名是整数,则该函数将返回带有整数键名的新数组,其键名以 0 开始进行重新索引