获取数组的前N个元素?


Answers:


359

使用array_slice()

这是PHP手册中的一个示例: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来避免这种情况。(第4个参数,自5.0.2起可用)。

例:

$output = array_slice($input, 2, 3, true);

输出:

array([3]=>'c', [4]=>'d', [5]=>'e');



4

最好尝试使用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));
?>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.