什么是最佳方法来实现这个?
使用array_slice()
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
只有一个小问题
如果数组索引对你很重要,记得 array_slice
会重置和重新排序数字数组索引。你需要将preserve_keys
标志设置为true
以避免这种情况。(第四个参数,自 PHP 5.0.2 以来可用)。
示例:
$output = array_slice($input, 2, 3, true);
输出:
array([3]=>'c', [4]=>'d', [5]=>'e');
array_slice() 是一个很好的尝试,以下是一些例子:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
如果你想获取数组中的前N个元素并将其从数组中移除,你可以使用array_splice()
函数(注意 "splice" 中的 'p'):
http://docs.php.net/manual/da/function.array-splice.php
使用方式如下:$array_without_n_elements = array_splice($old_array, 0, N)