PHP 获取数组的最后 3 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5468912/
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 get the last 3 elements of an array
提问by alex
I have an array:
我有一个数组:
[13] => Array
(
[0] => joe
[1] => 0
[14] => Array
(
[0] => bob
[1] => 0
)
[15] => Array
(
[0] => sue
[1] => 0
)
[16] => Array
(
[0] => john
[1] => 0
)
[17] => Array
(
[0] => harry
[1] => 0
)
[18] => Array
(
[0] => larry
[1] => 0
)
How can I get the last 3 elements while preserving the keys? (the number of elements in the array may vary, so I cannot simply slice after the 2nd element)
如何在保留键的同时获取最后 3 个元素?(数组中的元素数量可能会有所不同,所以我不能简单地在第二个元素之后切片)
So the output would be:
所以输出将是:
[16] => Array
(
[0] => john
[1] => 0
)
[17] => Array
(
[0] => harry
[1] => 0
)
[18] => Array
(
[0] => larry
[1] => 0
)
回答by Andreas Wong
If you want to preserve key, you can pass in true as the fourth argument:
如果要保留密钥,可以传入 true 作为第四个参数:
array_slice($a, -3, 3, true);
回答by fabrik
回答by codaddict
You can use array_slice
with offset as -3
so you don't have to worry about the array length also by setting preserve_keys
parameter to TRUE
.
您可以array_slice
与 offset 一起使用,-3
这样您也不必担心数组长度也可以通过将preserve_keys
参数设置为TRUE
.
$arr = array_slice($arr,-3,3,true);
回答by Silver Light
You can use array_slice():
您可以使用array_slice():
<?php
// -3 = start from the end
// true = preserve_keys
$result = array_slice($array, 0, -3, true);
?>