[英]How to get last key with values from array of arrays? PHP
这就是我目前正在使用的
<?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 print_r($sidebar)
; 我想获取最后一个 类别为 Array的数组并将其转换为链接。
我是php的新手,所以我的方法即使有效也可能是错误的。 我有一个正确的方法来拉类别数组或上面的代码是好的吗?
$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'
(而不是最后一个键),这似乎是最合乎逻辑的事情:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
我认为end()函数将是一个很好的解决方案: http : //php.net/manual/en/function.end.php它基本上返回要传递给它的数组中最后一个元素的值。
$sidebar = end($sidebar);
如果要获取键/值对而不弹出并推入数组,请将内部光标设置在数组的末尾,然后使用list
和each
来获取键和值。
// 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
也许结束 :
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
您可以使用`end()`代替`array_pop()`。 但是两者都适用于数组的“最后一个元素”。 唯一的区别是`end()`**指出了数组的最后一个元素**,而没有影响它,而`array_pop()`**使数组的最后一个元素弹出了**元素。 。
请通过以下链接获取详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.