2012-05-15 88 views
0

這裏新的數組是有問題的代碼:PHP從舊陣列

$countries = array("New Zealand", "Australia", "United Kingdom", "New Zealand"); 

我一些代碼,可以讓我宣佈從這個前一陣新的陣列我指定後數組中多少個項。

如:

如果我做了這樣的事情:

$newArray = $countries[1], $newArray will hold "New Zealand" and "Australia" 
$newArray = $countries[2], $newArray will hold "New Zealand", "Australia" and "United Kingdom" 

目前我使用一個for循環這樣做。有沒有更容易/更有效的方法來做到這一點?

感謝

回答

2

使用array_slice()

$array1 = array_slice($input, 0, 2); 
$array2 = array_slice($input, 0, 3); 
1

array_slice()是你在找什麼:

$countries = array("New Zealand", "Australia", "United Kingdom", "New Zealand"); 
$length = 3; 
$newArray = array_slice($countries, 0, $length); 
// $newArray == array("New Zealand", "Australia", "United Kingdom") 

http://php.net/array_slice