获取数组的前N个元素? [英] Get the first N elements of an array?
本文介绍了获取数组的前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');
这篇关于获取数组的前N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文