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
PHP: how to 'cut' my array?
提问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()
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 (0
means to start from the begining of the array).
第二个参数是起点(0
表示从数组的开头开始)。
The third parameter is the length of the resulting array. From the documentation:
第三个参数是结果数组的长度。从文档:
If
length
is given and is positive, then the sequence will have that many elements in it. Iflength
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 fromoffset
up until the end of thearray
.
如果
length
给定并且是正数,则序列中将包含那么多元素。如果length
给出并且是负数,则序列将从数组末尾停止那么多元素。如果省略,则序列将包含从offset
up 到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()
:
$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
回答by SubSevn
http://dev.fyicenter.com/faq/php/php_array_function_6.php
http://dev.fyicenter.com/faq/php/php_array_function_6.php
Look at the one about truncating, particularly array_splice
看看关于截断的那个,特别是array_splice