獲取PHP數組中的最后一個鍵-值對

[英]Get last key-value pair in PHP array


I have an array that is structured like this:

我有這樣一個數組:

[33] => Array
    (
        [time] => 1285571561
        [user] => test0
    )

[34] => Array
    (
        [time] => 1285571659
        [user] => test1
    )

[35] => Array
    (
        [time] => 1285571682
        [user] => test2
    )

How can I get the last value in the array, but maintaining the index [35]?

如何獲得數組中的最后一個值,而不維護索引[35]?

The outcome that I am looking for is this:

我想要的結果是:

[35] => Array
    (
        [time] => 1285571682
        [user] => test2
    )

8 个解决方案

#1


152  

try to use

嘗試使用

end($array);

#2


67  

$last = array_slice($array, -1, 1, true);

See http://php.net/array_slice for details on what the arguments mean.

有關參數的詳細信息,請參見http://php.net/array_slice。

P.S. Unlike the other answers, this one actually does what you want. :-)

附注:與其他答案不同的是,這個答案實際上是你想要的。:-)

#3


10  

You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:

您可以使用end將內部指針提前到end或array_slice,以獲得只包含最后一個元素的數組:

$last = end($arr);
$last = current(array_slice($arr, -1));

#4


4  

If you have an array

如果你有一個數組

$last_element = array_pop(array);

#5


2  

Like said Gumbo,

像秋葵說,

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

#6


2  

// if your array keys lile
// 0 1 2 3 4 ...

$lastindex= count($ar)-1;

// but if you are not sure

$ar_k=array_keys($ar);
$lastindex=$ar_k[count($ar_k)-1];

// will work

#7


1  

Another solution cold be:

另一個解決方案冷是:

$value = $arr[count($arr) - 1];

The above will count the amount of array values, substract 1 and then return the value.

上面將計算數組值的數量,substract 1,然后返回值。

Note: This can only be used if your array keys are numeric.

注意:只有當數組鍵是數值的時候才可以使用。

#8


0  

As the key is needed, the accepted solution doesn't work.

因為需要密鑰,所以可接受的解決方案不能工作。

This:

這樣的:

end($array);
return array(key($array) => array_pop($array));

will return exactly as the example in the question.

將返回與問題中的示例完全相同的結果。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/09/27/37b402d92565f74e871779fdd2b47b67.html



 
  © 2014-2022 ITdaan.com 联系我们: