PHP合並數組我們可以使用array_merge()函數,array_merge()函數返回一個聯合的數組。所得到的數組以第一個輸入數組參數開始,按後面數組參數出現的順序依次追加。其形式為:
array array_merge (array array1 array2…,arrayN)
下面是一個PHP合並數組的例子:
1
2$fruits = array("apple","banana","pear");
3$numbered = array("1","2","3");
4$cards = array_merge($fruits, $numbered);
5print_r($cards);
6// 輸出結果:
7// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
8?>
用PHP追加數組,使用array_merge_recursive(),將兩個數組合並在一起,注意,與array_merge()函數是不一樣的,array_merge()的兩個數組有重復項時會覆蓋掉,而array_merge_recursive()則不會。array_merge_recursive()語法:
array array_merge_recursive(array array1,array array2[…,array arrayN])
下面是一個PHP追加數組的例子:
1
2$fruit1 = array("apple" => "red", "banana" => "yellow");
3$fruit2 = array("pear" => "yellow", "apple" => "green");
4$result = array_merge_recursive($fruit1, $fruit2);
5print_r($result);
6// 輸出結果:
7// Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
8?>
現在apple 指向一個數組,由兩個顏色值組成的索引數組。