来自旧数组的PHP新数组

时间:2012-05-15 00:42:25

标签: 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循环来完成此操作。有没有更简单/更有效的方法来做到这一点?

感谢

3 个答案:

答案 0 :(得分:2)

使用array_slice()

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

答案 1 :(得分: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

答案 2 :(得分:0)

您可以使用array_slice将其解压缩