當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP array_merge_recursive()用法及代碼示例

array_merge_recursive()是PHP中的內置函數,用於將兩個或多個數組遞歸合並為一個數組。此函數用於將兩個或多個數組的元素或值合並到一個數組中。合並的方式是將一個數組的值附加到前一個數組的末尾。如果給定數組中有相同的鍵,則為鍵分配一個值,該值具有一個數組,該數組由具有相同鍵的值組成。

注意:該函數與array_merge()的不同之處在於,在具有相同鍵的多個數組的情況下,array_merge()函數從所有數組中獲取最後一個數組值,但是在array_merge_recursive()中,該鍵被分配了一個數組,該數組由具有以下各項的所有數組值組成相同的鍵。

用法:


array_merge_recursive($array1, $array2, $array3...$arrayn)

參數:該函數可以采用任意數量的數組作為參數,並以逗號(,)分隔,我們需要合並這些數組。第一個參數$array1是必需的。

返回值:該函數返回合並了所有數組的合並數組。合並的方式是將一個數組的值附加到前一個數組的末尾。如果給定數組中有相同的鍵,則將為輸出數組中的鍵分配一個數組,該數組由具有相同鍵的值組成。

例子:

Input : $a1=array("a"=>"raj", "b"=>"striver");
        $a2=array("z"=>"geeks", "b"=>"articles");
Output : 
Array
(
    [a] => raj
    [b] => Array
        (
            [0] => striver
            [1] => articles
        )

    [z] => geeks
)
Explanation: "striver" and "articles" has the same 
key "b", so the key b is assigned to an array which has 
"striver" and "articles" as elements. 

Input :$a1=array("a"=>"raj", "b"=>"striver");
       $a2=array("z"=>"geeks", "d"=>"articles");
Output :
Array
(
    [a] => raj
    [b] => striver
    [z] => geeks
    [d] => articles
)

以下示例程序旨在說明array_merge_recursive()函數:

程序1:PHP程序演示array_merge_recursive()
具有所有不同按鍵的函數。

<?php 
// PHP program to demonstrate array_merge_recursive()  
// function with same keys 
$a1=array("a"=>"raj", "b"=>"striver"); 
$a2=array("z"=>"geeks", "d"=>"articles"); 
  
print_r(array_merge_recursive($a1, $a2)); 
?>

輸出:

Array
(
    [a] => raj
    [b] => striver
    [z] => geeks
    [d] => articles
)

程序2:PHP程序,用相同的鍵演示array_merge_recursive()函數。

<?php 
// PHP program to demonstrate array_merge_recursive()  
// function with same keys 
$a1=array("a"=>"raj", "b"=>"striver"); 
$a2=array("z"=>"geeks", "b"=>"articles"); 
  
//function call 
print_r(array_merge_recursive($a1, $a2)); 
?>

輸出:

Array
(
    [a] => raj
    [b] => Array
        (
            [0] => striver
            [1] => articles
        )

    [z] => geeks
)

參考:
http://php.net/manual/en/function.array-merge-recursive.php



相關用法


注:本文由純淨天空篩選整理自Striver大神的英文原創作品 PHP | array_merge_recursive() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。