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

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

PHP get the last 3 elements of an array

phparrays

提问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

Use array_slice:

使用array_slice

$res = array_slice($array, -3, 3, true);

回答by codaddict

You can use array_slicewith offset as -3so you don't have to worry about the array length also by setting preserve_keysparameter 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); 
?>