使用 PHP - SPL 解决方案反向迭代数组? [英] Iterate in reverse through an array with PHP - SPL solution?

查看:22
本文介绍了使用 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));
    }
}

不使用 array_reverse 但通过标准数组函数迭代数组的稍长实现是

A slightly longer implementation that doesn't use array_reverse but iterates the array via the standard array functions would be

class ReverseArrayIterator implements Iterator
{
    private $array;

    public function __construct(array $array)
    {
        $this->array = $array;
    }

    public function current()
    {
        return current($this->array);
    }

    public function next()
    {
        return prev($this->array);
    }

    public function key()
    {
        return key($this->array);
    }

    public function valid()
    {
        return key($this->array) !== null;
    }

    public function rewind()
    {
        end($this->array);
    }
}

这篇关于使用 PHP - SPL 解决方案反向迭代数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆