使用 PHP - SPL 解决方案反向迭代数组?
PHP 中有 SPL 反向数组迭代器吗? 如果没有,实现这一目标的最佳方法是什么?
我可以简单地做
$array = array_reverse($array);
foreach($array as $currentElement) {}
或者
for($i = count($array) - 1; $i >= 0; $i--)
{
}
但是有更优雅的方法吗?
Is there an SPL Reverse array iterator in PHP?
And if not, what would be the best way to achieve it?
I could simply do
$array = array_reverse($array);
foreach($array as $currentElement) {}
or
for($i = count($array) - 1; $i >= 0; $i--)
{
}
But is there a more elegant way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
这是一个不复制也不修改数组的解决方案:
如果您还想要对当前键的引用:
这始终有效,因为 php 数组键永远不会为空,并且比此处给出的任何其他答案更快。
Here is a solution that does not copy and does not modify the array:
If you also want a reference to the current key:
This works always as php array keys can never be null and is faster than any other answer given here.
没有
ReverseArrayIterator
可以做到这一点。您可以将其放入您自己的自定义迭代器中,例如,
不使用 array_reverse 但通过标准数组函数迭代数组的稍长的实现将是
There is no
ReverseArrayIterator
to do that. You can door make that into your own custom iterator, e.g.
A slightly longer implementation that doesn't use
array_reverse
but iterates the array via the standard array functions would be根据 linepogl 的答案,我想出了这个函数:
用法:
这适用于数组和其他可迭代对象,无需先进行复制它的。
Based on linepogl's answer, I came up with this function:
Usage:
This works on arrays and other iterables without first making a copy of it.
根据您想要执行的操作,您可能需要研究 spl 数据结构类,例如 SplStack。 SplStack 实现了 Iterator、ArrayAccess 和 Countable,因此它主要可以像数组一样使用,但默认情况下,它的迭代器按 FILO 顺序进行。例如:
这将打印
Depending on what you are trying to do, you might want to look into the spl data structure classes, such as SplStack. SplStack implements Iterator, ArrayAccess and Countable, so it can mostly be used like an array, but by default, its iterator proceeds in FILO order. Ex:
This will print
请注意,如果要保留数组的键,则必须将
true
作为第二个参数传递给array_reverse
:Note that if you want to preserve the keys of the array, you must pass
true
as the second parameter toarray_reverse
:基于linepogl的答案...您可以通过避免
current()
调用来提高效率Based on linepogl's answer... You can make it even more efficient by avoiding
current()
call这是更好的使用方法。如果键不是连续的或整数,它也会处理它们。
This is better way to use. It will take care of keys also, if they are not sequential or integer.
这可能是一种更高效的方法,因为它不构造新数组。它还可以很好地处理空数组。
This could be a more performant way since it doesnt construct a new array. It also handles empty arrays well.
$array1= 数组(10,20,30,40,50);
$array1= array(10,20,30,40,50);