• php 合并数组 "+"和"array_merge"的区别


    主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意

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

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

    <?php
    $array1 = array(=> 'zero_a'=> 'two_a'=> 'three_a');
    $array2 = array(=> 'one_b'=> 'three_b'=> '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"
    }


    <?php
    $array1 = array("color" => "red"24);
    $array2 = array("a""b""color" => "green""shape" => "trapezoid"4);
    $result array_merge($array1$array2);
    print_r($result);
    ?>
     
    结果:
    Array
    (
        [color] => green
        [0] => 2
        [1] => 4
        [2] => a
        [3] => b
        [shape] => trapezoid
        [4] => 4
    )


    http://www.php.net/manual/zh/function.array-merge.php

    另有函数array_merge_recursive()可对比学习。
  • 相关阅读:
    linux学习笔记
    HDMI之CEC DDC学习笔记(可能有误)
    MAP按照value排序
    Map遍历四种方法
    Java native方法
    [PAT] 1143 Lowest Common Ancestor (30 分)Java
    [PAT] 1148 Werewolf
    [PAT] 1096 Consecutive Factors (20 分)Java
    [PAT] 1092 To Buy or Not to Buy (20 分)Java
    [PAT] 1088 Rational Arithmetic (20 分)Java
  • 原文地址:https://www.cnblogs.com/eterwei/p/3822268.html
Copyright © 2020-2023  润新知