zoukankan      html  css  js  c++  java
  • 合并两个数组的两种方式的异同

    合并数组的两种方式:$a+$b , array_merge($a,$b)

    合并索引数组使用操作符+,有重复的索引会被丢弃;使用array_merge() 重复索引会被重置,如下面这种情况:

     1 php > $a = array();  
     2 
     3 php > $b = array(1=>'data');  
     4 
     5 php > $c = $a+$b;  
     6 
     7 php > $d = array_merge($a,$b);  
     8 
     9 php > var_dump($c,$d);  
    10 
    11 //输出结果
    12 
    13 array(1) {  [1] =>  string(4) "data" }  
    14 
    15 array(1) {  [0] =>  string(4) "data" }  

    所以,当使用+来合并两个索引数组,值可能会被丢弃,而array_merge就不会,会把重复的索引重置:

     1 php > $a = array(1=>'one',2=>'two',3=>'three');  
     2 php > $b = array(3=>'three',4=>'four',5=>'five');  
     3 php > $c = $a+$b;  
     4 php > $d = array_merge($a,$b);  
     5 php > var_dump($c,$d);  
     6 array(5) {  
     7   [1] =>  string(3) "one"  
     8   [2] =>  string(3) "two"  
     9   [3] =>  string(5) "three"  
    10   [4] =>  string(4) "four"  
    11   [5] =>  string(4) "five"  
    12 }  
    13 
    14 array(6) {  
    15   [0] =>  string(3) "one"  
    16   [1] =>  string(3) "two"  
    17   [2] =>  string(5) "three"  
    18   [3] =>  string(5) "three"  
    19   [4] =>  string(4) "four"  
    20   [5] =>  string(4) "five"  
    21 }  
  • 相关阅读:
    归并排序——计算逆序数
    二分图 (匈牙利算法)
    拓扑排序
    读入外挂——秒杀scanf
    最小生成树(kruskal+并查集)
    最短路算法(dijkstra,bellman_ford,floyd)
    【Python】【Module】re
    【Python】【Module】os
    【Python】【Module】random
    【Python】【Module】time
  • 原文地址:https://www.cnblogs.com/hellodp/p/5537480.html
Copyright © 2011-2022 走看看