php数组(一) array_merge

array_merge合并数组,几大特点验证:

1、如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。如果输入的数组存在以数字作为索引的内容,则这项内容的键名会以连续方式重新索引。

 

<?php
$array1 = array("color" => "red", 2, 4 => 'first');
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4 => 'second');
$result = array_merge($array1, $array2);
print_r($result);
?>

输出结果为: 其中key为4的元素没有被覆盖,而是被重新索引,字符串类型的key被覆盖了

Array
(
    [color] => green
    [0] => 2
    [1] => first
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => second
)

 

2、使用+与使用array_merge的区别

<?php
$array1 = array("color" => "red", 2, 4 => 'first');
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4 => 'second');
$result = $array1 + $array2;
print_r($result);
?>

 输出为:如果key已经存在,数组2的元素不会覆盖数组1的元素

Array
(
    [color] => red
    [0] => 2
    [4] => first
    [1] => b
    [shape] => trapezoid
)

 

3、如果数字为key则会重新索引,如何避免不被重新索引,使用+

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

 输出为:第一个数组的键名将会被保留。在两个数组中存在相同的键名时,第一个数组中的同键名的元素将会被保留,第二个数组中的元素将会被忽略。

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

 

posted on 2021-08-02 20:28  1450811640  阅读(38)  评论(0编辑  收藏  举报