查找关联数组中的最后一对
我正在使用 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
}
I'm looping through an associative array with a foreach. I'd like to be able to check if the key value pair being handled is the last so I can give it special treatment. Any ideas how I can do this the best way?
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
就这么简单,没有计数器和其他“黑客”。
请注意,您必须使用
===
,因为函数next()
可能会返回一个非布尔值,该值计算结果为false
,例如
0
或“”(空字符串)。Simple as this, free from counters and other 'hacks'.
Please note that you have to use
===
, because the functionnext()
may return a non-boolean value which evaluates tofalse
, such as0
or "" (empty string).我们不需要使用 foreach 遍历数组,我们可以使用 end()、key() 和 current() php 函数来获取最后一个元素并获取它的 key + value。
如果你想在迭代中检查它,end()函数仍然有用:
we don't need to iterate through the array with foreach, we can use the end(), key() and current() php functions to get to the last element and get it's key + value.
If you want to check it in the iteration, the end() function still can be useful:
假设你在迭代数组时没有改变数组,你可以维护一个在循环中递减的计数器,一旦它达到 0,你就可以处理最后一个:
Assuming you're not altering the array while iterating through it, you could maintain a counter that decrements in the loop and once it reaches 0, you're handling the last:
正如其他答案无疑会表明的那样,有很多方法可以做到这一点。但我建议学习 SPL 及其 缓存迭代器。这是一个例子:
它比简单的 foreach 更详细,但也不是那么详细。一旦您学习了所有不同的 SPL 迭代器,它们就会为您打开一个全新的世界 :) 这是一个很好的教程。
There are quite a few ways to do that as other answers will no doubt show. But I would suggest to learn SPL and its CachingIterator. Here is an example:
It is more verbose than simple foreach, but not all that much. And all the different SPL iterators open up a whole new world for you, once you learn them :) Here is a nice tutorial.
您可以使用数组指针遍历函数(特别是
next
) 来确定当前元素之后是否还有另一个元素:请注意,如果数组包含值为
FALSE
的元素,则此方法将不起作用,并且您需要处理执行通常的循环体后的最后一个元素(因为通过调用next
使数组指针前进),或者记住该值。You could use the array pointer traversal functions (specifically
next
) to determine if there is another element after the current one:Note that this method won't work if your array contains elements whose value is
FALSE
, and you'll need to handle the last element after doing your usual loop body (because the array pointer is advanced by callingnext
) or else memoize the value.