PHP:如何“切割”我的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3585966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:19:04  来源:igfitidea点击:

PHP: how to 'cut' my array?

phparrays

提问by aneuryzm

I have an array

我有一个数组

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

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

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

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

Thanks

谢谢

回答by ircmaxell

Check out array_slice()

查看 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);

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

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

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

第三个参数是结果数组的长度。从文档:

If lengthis given and is positive, then the sequence will have that many elements in it. If lengthis 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 offsetup until the end of the array.

如果length给定并且是正数,则序列中将包含那么多元素。如果length给出并且是负数,则序列将从数组末尾停止那么多元素。如果省略,则序列将包含从offsetup 到array.

回答by BoltClock

Slice it. With a knife.

切片。用刀。

Actually, with this:

实际上,有了这个:

array_slice($array, 0, -3);

Assuming you meant cutting off the last 3elements.

假设您的意思是切断最后3 个元素。

回答by cletus

Use array_splice():

使用array_splice()

$new = array_splice($old, 0, 3);

The above line returns the first three elements of $old.

上面的行返回 的前三个元素$old

Important:array_splice()modifies the original array.

重要:array_splice()修改原始数组。

回答by codaddict

Use array_spliceas:

使用array_splice作为:

$array = array(0,1,2,3,4,5);
array_splice($array,0,3);

回答by SubSevn