我正在用foreach遍歷一個關聯數組。我希望能夠檢查正在處理的關鍵值對是否是最後一個,以便我可以給予特殊處理。任何想法我怎麼能做到這一點最好的方式?在關聯數組中找到最後一對
foreach ($kvarr as $key => $value){
// I'd like to be able to check here if this key value pair is the last
// so I can give it special treatment
}
我正在用foreach遍歷一個關聯數組。我希望能夠檢查正在處理的關鍵值對是否是最後一個,以便我可以給予特殊處理。任何想法我怎麼能做到這一點最好的方式?在關聯數組中找到最後一對
foreach ($kvarr as $key => $value){
// I'd like to be able to check here if this key value pair is the last
// so I can give it special treatment
}
假設你在迭代時不改變數組,你可以維護一個在循環中遞減的計數器,一旦達到0,你正在處理最後:
<?php
$counter = count($kvarr);
foreach ($kvarr as $key => $value)
{
--$counter;
if (!$counter)
{
// deal with the last element
}
}
?>
有很多方法可以做到這一點,因爲其他答案無疑會顯示出來。但我會建議學習SPL及其CachingIterator。這裏是一個例子:
<?php
$array = array('first', 'second', 'third');
$object = new CachingIterator(new ArrayIterator($array));
foreach($object as $value) {
print $value;
if (!$object->hasNext()) {
print "<-- that was the last one";
}
}
它比簡單的foreach更詳細,但不是那麼多。所有不同的SPL迭代器爲你打開了一個全新的世界,一旦你瞭解它們:)Here is a nice tutorial.
看起來有趣,這PSL的事情,將着眼於儘快學習英語。 – Chris 2009-10-30 19:05:04
你可以使用數組指針遍歷功能(特別是next
),以確定是否有是當前一個又一個元素:
$value = reset($kvarr);
do
{
$key = key($kvarr);
// Do stuff
if (($value = next($kvarr)) === FALSE)
{
// There is no next element, so this is the last one.
}
}
while ($value !== FALSE)
沒有如果數組包含的元素的值爲FALSE
,並且在完成常用循環體(因爲通過調用next
來提前數組指針)之前需要處理最後一個元素,否則此方法將不起作用,否則請記住該值。
這樣簡單,沒有櫃檯和其他'黑客'。
foreach ($array as $key => $value) { // your stuff if (next($array) === false) { // this is the last iteration } }
請注意,您必須使用===
,因爲函數next()
可以返回一個非布爾值計算結果爲false
,如0
或「」(空字符串)。
這個/幾乎適用於我,它看起來像foreach()在設置$ key&$ value之後將內部數組指針提前到下一個項目,因此next()觸發倒數第二項:http://codepad.org/wAWVF61k ps。我怎樣才能在評論中設置多行代碼的格式? – MSpreij 2016-03-21 11:00:00
我們不需要用foreach遍歷數組,我們可以使用end(),key()和current()php函數來獲取最後一個元素並獲取它的鍵+值。
<?php
$a = Array(
"fruit" => "apple",
"car" => "camaro",
"computer" => "commodore"
);
// --- go to the last element of the array & get the key + value ---
end($a);
$key = key($a);
$value = current($a);
echo "Last item: ".$key." => ".$value."\n";
?>
如果你要檢查它的迭代,end()函數依然可以是有用的:
foreach ($a as $key => $value) {
if ($value == end($a)) {
// this is the last element
}
}
'end()'將內部指針移動到數組的末尾,這意味着'foreach()'只會執行** 1次迭代**並退出。只要調用'end()',它就會「快進」到數組的末尾,這可能會導致出現問題,因爲實際上您確實想要對其他元素執行某些操作。例如:http://codepad.org/UubOTgXl – 2015-07-17 17:16:59
我們不需要用foreach遍歷整個數組。我們可以使用end(),key()和current()命令來獲取最後一個元素的鍵/值信息。請參閱下面的答案並附上詳細的示例。 – 2012-05-18 22:32:53
當你檢查最後一條記錄時,這是一個很好的例子。 – 2013-07-08 09:38:06