Iterate in reverse through an array with PHP - SPL solution?

后端 未结 11 2001
清酒与你
清酒与你 2020-12-05 13:51

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)         


        
11条回答
  •  一个人的身影
    2020-12-05 14:22

    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));
        }
    }
    

    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);
        }
    }
    

提交回复
热议问题