使用PHP-SPL解决方案反向遍历数组? [英] Iterate in reverse through an array with PHP - SPL solution?
本文介绍了使用PHP-SPL解决方案反向遍历数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PHP中是否有SPL反向数组迭代器? 如果没有,那么实现它的最佳方法是什么?
Is there an SPL Reverse array iterator in PHP? And if not, what would be the best way to achieve it?
我可以做
$array = array_reverse($array);
foreach($array as $currentElement) {}
或
for($i = count($array) - 1; $i >= 0; $i--)
{
}
但是还有更优雅的方法吗?
But is there a more elegant way?
推荐答案
没有ReverseArrayIterator
可以做到这一点.你可以做
There is no ReverseArrayIterator
to do that. You can do
$reverted = new ArrayIterator(array_reverse($data));
或将其放入您自己的自定义迭代器中,例如
or make that into your own custom iterator, e.g.
class ReverseArrayIterator extends ArrayIterator
{
public function __construct(array $array)
{
parent::__construct(array_reverse($array));
}
}
这篇关于使用PHP-SPL解决方案反向遍历数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文