一張截圖概括A+B與array_merge(A,B)的區別

zhaiduting發表於2020-07-24

Laravel
merge操作:相同的字元鍵改寫,相同的數字鍵重新編號;
+號操作:B類似於候補選手,如果B中的鍵在A中存在,則B的這對鍵值沒機會上場

再看array_merge_recursive(A,B)

array_merge_recursive(
  [
    "a" => "red",
    "b" => [
        "green",
      ]
  ],
  [
    "c" => "blue",
    "b" => [
        "yellow",
      ]
  ]
);

/* 結果如下
   [
     "a" => "red",
     "b" => [
       "green",
       "yellow",
     ],
     "c" => "blue",
   ]
*/
array_merge_recursive(
  [ "b" => "green"],
  [ "b" =>
      ["yellow"]
  ]
);

/* 合併後 b 的鍵值並不是 ["green", ["yellow"]] 而是下面這樣
   [
     "b" => [
       "green",
       "yellow",
     ],
   ]
*/
array_merge_recursive(
  "green",
  [
    "yellow"
  ]
);

//報錯 Expected parameter 1 to be an array
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章