PHP得到一个数组的第N个元素? [英] php get the first N elements of an array?

查看:565
本文介绍了PHP得到一个数组的第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 标记设置为真正来避免这种情况。 (第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');

这篇关于PHP得到一个数组的第N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆