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

use*_*303 0 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 } ?>
Run Code Online (Sandbox Code Playgroud)

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

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

dec*_*eze 5

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

更新后:

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

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

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

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