PHP中array_merge合并两个数组的程序

合并数据在php中我们利用array_merge()函数来实现,array_merge() 函数把两个或多个数组合并为一个数组. 如果键名有重复,该键的键值为最后一个键名对应的值(后面的覆盖前面的).如果数组是数字索引的,则键名会以连续方式重新索引.

实例代码如下:

  1. <?php
  2. echo "rn第一种情况rn";
  3. $a=array(1,2,3,4,5,6);
  4. $b=array(7,8,9);
  5. $c=array_merge ($a,$b);
  6. print_r($c);
  7. $c=$a+$b;
  8. print_r($c);
  9. $c=$b+$a;
  10. print_r($c);
  11. echo "rn第二种情况rn";
  12. $a=array('a','b','c','d','e','f');
  13. $b=array('a','x','y');
  14. $c=array_merge ($a,$b);
  15. print_r($c);
  16. $c=$a+$b;
  17. print_r($c);
  18. $c=$b+$a;
  19. print_r($c);
  20. echo "rn第三种情况rn";
  21. $a=array(
  22. 1=>'a',
  23. 2=>'b',
  24. 3=>'c',
  25. 4=>'d',
  26. 5=>'e',
  27. 6=>'f');
  28. $b=array(
  29. 1=>'a',
  30. 7=>'x',
  31. 8=>'y');
  32. $c=array_merge ($a,$b);
  33. print_r($c);
  34. $c=$a+$b;
  35. print_r($c);
  36. $c=$b+$a;
  37. print_r($c);
  38. ?>
  39. 结果如下:
  40. 第一种情况
  41. Array
  42. (
  43. [0] => 1
  44. [1] => 2
  45. [2] => 3
  46. [3] => 4
  47. [4] => 5
  48. [5] => 6
  49. [6] => 7
  50. [7] => 8
  51. [8] => 9
  52. )
  53. Array
  54. (
  55. [0] => 1
  56. [1] => 2
  57. [2] => 3
  58. [3] => 4
  59. [4] => 5
  60. [5] => 6
  61. )
  62. Array
  63. (
  64. [0] => 7
  65. [1] => 8
  66. [2] => 9
  67. [3] => 4
  68. [4] => 5
  69. [5] => 6
  70. )
  71. 第二种情况
  72. Array
  73. (
  74. [0] => a
  75. [1] => b
  76. [2] => c
  77. [3] => d
  78. [4] => e
  79. [5] => f
  80. [6] => a
  81. [7] => x
  82. [8] => y
  83. )
  84. Array
  85. (
  86. [0] => a
  87. [1] => b
  88. [2] => c
  89. [3] => d
  90. [4] => e
  91. [5] => f
  92. )
  93. Array
  94. (
  95. [0] => a
  96. [1] => x
  97. [2] => y
  98. [3] => d
  99. [4] => e
  100. [5] => f
  101. )
  102. 第三种情况
  103. Array
  104. (
  105. [0] => a
  106. [1] => b
  107. [2] => c
  108. [3] => d
  109. [4] => e
  110. [5] => f
  111. [6] => a
  112. [7] => x
  113. [8] => y
  114. )
  115. Array
  116. (
  117. [1] => a
  118. [2] => b
  119. [3] => c
  120. [4] => d
  121. [5] => e
  122. [6] => f
  123. [7] => x
  124. [8] => y
  125. )
  126. Array
  127. (
  128. [1] => a
  129. [7] => x
  130. [8] => y
  131. [2] => b
  132. [3] => c
  133. [4] => d
  134. [5] => e
  135. [6] => f
  136. )

1)键名为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)

2)键名为字符时,+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值

注释:如果仅仅向 array_merge() 函数输入了一个数组,且键名是整数,则该函数将返回带有整数键名的新数组,其键名以 0 开始进行重新索引