获取数组的前 N ​​个元素?

获取数组的前 N ​​个元素?

问题描述:

实现这一目标的最佳方法是什么?

What is the best way to accomplish this?

使用 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 将重置和重新排序 numeric 数组索引.您需要将 preserve_keys 标志设置为 true 以避免这种情况.(第 4 个参数,从 5.0.2 开始可用).

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag set to trueto avoid this. (4th parameter, available since 5.0.2).

示例:

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

输出:

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