首頁  >  文章  >  後端開發  >  PHP數組合併的其他擴充函數有什麼?

PHP數組合併的其他擴充函數有什麼?

王林
王林原創
2024-04-28 11:57:021034瀏覽

PHP 提供了 3 個合併數組的擴充函數:array_merge_recursive() 遞歸合併數組,array_replace() 覆寫相同鍵名的值,array_replace_recursive() 遞歸覆寫數組中的值。

PHP數組合併的其他擴充函數有什麼?

PHP 數字組合並的其他擴充函數

除了array_merge() 函數外,PHP 還提供了其他擴充函數來合併數組。這些函數提供了不同的合併選項,可用於處理更複雜的情況。

1. array_merge_recursive()

# 此函式遞歸合併兩個或多個陣列。與 array_merge() 不同,它不會覆蓋現有的鍵名,而是將它們的子數組合併到最終結果中。

$arr1 = ['a' => 1, 'b' => ['c' => 3, 'd' => 4]];
$arr2 = ['a' => 2, 'b' => ['e' => 5, 'f' => 6]];

$result = array_merge_recursive($arr1, $arr2);

var_dump($result);

#輸出:

array(2) {
  ["a"]=>
  int(2)
  ["b"]=>
  array(3) {
    ["c"]=>
    int(3)
    ["d"]=>
    int(4)
    ["e"]=>
    int(5)
  }
}

2. array_replace()

此函數以第二個陣列取代第一個陣列中的相同鍵名的值。它不會合併數組,而是將第一個數組中的值覆蓋為第二個數組中的值。

$arr1 = ['a' => 1, 'b' => 2, 'c' => 3];
$arr2 = ['b' => 4, 'd' => 5];

$result = array_replace($arr1, $arr2);

var_dump($result);

#輸出:

array(4) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(4)
  ["c"]=>
  int(3)
  ["d"]=>
  int(5)
}

3. array_replace_recursive()

此函數類似於array_replace(),但它遞歸替換數組中的值。這意味著子數組中的值也會被替換。

$arr1 = ['a' => 1, 'b' => ['c' => 3, 'd' => 4]];
$arr2 = ['b' => ['e' => 5, 'f' => 6]];

$result = array_replace_recursive($arr1, $arr2);

var_dump($result);

輸出:

array(2) {
  ["a"]=>
  int(1)
  ["b"]=>
  array(2) {
    ["e"]=>
    int(5)
    ["f"]=>
    int(6)
  }
}

以上是PHP數組合併的其他擴充函數有什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn