PHP合並數組我們可以使用array_merge()函數,array_merge()函數返回一個聯合的數組。所得到的數組以第一個輸入數組參數開始,按後面數組參數出現的順序依次追加。其形式為:
array array_merge (array array1 array2…,arrayN)
下面是一個PHP合並數組的例子:
代碼如下 復制代碼<?php
$fruits = array("apple","banana","pear");
$numbered = array("1","2","3");
$cards = array_merge($fruits, $numbered);
print_r($cards);
// 輸出結果:
// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
?>
用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追加數組的例子:
代碼如下 復制代碼<?php
$fruit1 = array("apple" => "red", "banana" => "yellow");
$fruit2 = array("pear" => "yellow", "apple" => "green");
$result = array_merge_recursive($fruit1, $fruit2);
print_r($result);
// 輸出結果:
// Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
?>
現在apple 指向一個數組,由兩個顏色值組成的索引數組,還有一種比較怪的做法就是合並數組
array_splice()語法格式為:
array array_splice ( array array , int offset[,length[,array replacement]])
例子
代碼如下 復制代碼<?php
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_splice($fruits, 4);
print_r($fruits);
print_r($subset);
// 輸出結果為:
// Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
// Array ( [0] => Grape [1] => Lemon [2] => Watermelon )
?>
我們還可以使用可選參數replacement來指定取代目標部分的數組。請看下面的例子:
代碼如下 復制代碼<?php
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));
print_r($fruits);
print_r($subset);
// 輸出結果:
// Array ( [0] => Apple [1] => Banana [2] => Green Apple [3] => Red Apple [4] => Watermelon )
// Array ( [0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
?>