如何使用数组数组中的值获取最后一个键? PHP

时间:2011-03-03 02:52:54

标签: php arrays key

这就是我目前使用的

<?php $sidebar = $this->data['sidebar']; 
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
    if ($item['active']) { ?> class="active"<?php } ?>><a href="<?php echo htmlspecialchars($item['href']) ?>"><?php echo htmlspecialchars($item['text']) ?></a></li>
<?php } ?>

当我print_r($sidebar)时,这就是我得到的(http://pastebin.com/t6Y2ZtMF); 我想获得最后一个数组,这是 Categories 并将其转换为链接。

我是php的新手,所以我的方法可能是错误的,即使它有效。我有一个正确的方法来拉类别数组或上面的代码是好的吗?

5 个答案:

答案 0 :(得分:5)

$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()

更新后:

您似乎不需要密钥,只需要数组:

<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
    business as usual...
<?php endforeach; ?>

既然你知道你想要密钥'Categories'(而不是 last 密钥),这似乎是最合乎逻辑的事情:

<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
    business as usual...
<?php endforeach; ?>

答案 1 :(得分:2)

我认为end()函数是一个很好的解决方案:http://php.net/manual/en/function.end.php 它基本上返回传递给它的数组中最后一个元素的值。

$sidebar = end($sidebar);

答案 2 :(得分:2)

如果你想得到一个没有弹出的键值/值对&amp;推送数组,将内部光标设置到数组的末尾,然后使用listeach获取密钥&amp;值。

// set up your array however you had it
$array = ...;

// move the cursor to the end of the array
end($array);

// use list() and each() to extract your key/value pair    
list($key,$val) = each($array);  

// $key will now have the last key
// $val will have the last value

答案 3 :(得分:1)

或许,end

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

答案 4 :(得分:1)

您可以使用`end()`而不是`array_pop()`。但两者都适用于阵列的**最后一个元素**。唯一的区别是`end()`**指出**数组的**最后一个元素**而不影响它而``array_pop()`**弹出**元素的**结尾**

请浏览以下链接以获取详细信息

end() | array_pop()