PHP:如何“切割"我的数组? [英] PHP: how to 'cut' my array?

查看:23
本文介绍了PHP:如何“切割"我的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

如何删除最新的 2 个单元格并使其更短?

How can I remove the latest 2 cells and make it shorter ?

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)

谢谢

推荐答案

查看 array_slice()

所以,如果你只想要前三个元素:

So, if you wanted the first three elements only:

$array = array_slice($array, 0, 3);

如果你想要除了最后三个元素之外的所有元素:

If you wanted all but the last three elements:

$array = array_slice($array, 0, -3);

第二个参数是起点(0表示从数组的开头开始).

The second parameter is the start point (0 means to start from the begining of the array).

第三个参数是结果数组的长度.来自文档:

The third parameter is the length of the resulting array. From the documentation:

如果给定 length 并且是正数,那么序列将有那么多其中的元素.如果给定 length 并且为负数,则序列将从数组的末尾停止那么多元素.如果省略,则序列将包含从 offsetarray 结束的所有内容.

If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

这篇关于PHP:如何“切割"我的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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