获取数组的前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
将重置并重新排列数字数组索引.您需要将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 true
to avoid this. (4th parameter, available since 5.0.2).
示例:
$output = array_slice($input, 2, 3, true);
输出:
array([3]=>'c', [4]=>'d', [5]=>'e');