0

这是有问题的代码:

$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 循环来做到这一点。有没有更简单/更有效的方法来做到这一点?

谢谢

4

3 回答 3

2

采用array_slice()

$array1 = array_slice($input, 0, 2);
$array2 = array_slice($input, 0, 3);
于 2012-05-15T00:47:59.343 回答
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

于 2012-05-15T00:47:46.170 回答
0

你可以使用array_slice来提取它

于 2012-05-15T00:48:37.643 回答