获取数组的前 N 个元素? [英] Get the first N elements of an array?
本文介绍了获取数组的前 N 个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
实现这一目标的最佳方法是什么?
What is the best way to accomplish this?
推荐答案
使用 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 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屋!
查看全文