簡體   English   中英

如何從數組數組中獲取帶有值的最后一個鍵? 的PHP

[英]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);

如果要獲取鍵/值對而不彈出並推入數組,請將內部光標設置在數組的末尾,然后使用listeach來獲取鍵和值。

// 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()`**使數組的最后一個元素彈出了**元素。 。

請通過以下鏈接獲取詳細信息

end() | array_pop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM