代码之家  ›  专栏  ›  技术社区  ›  Jay Bienvenu

使用递归迭代器遍历作为属性值的数组

php
  •  0
  • Jay Bienvenu  · 技术社区  · 6 年前

    我正在开发一个内容迭代器,它应该递归到数组中,并将每个值作为单独的迭代返回。这是我们班的一个精简版:

    class ContentIterator extends \RecursiveIteratorIterator
    {
        private $_ordinal = 0;
    
        public function __construct()
        {
            parent::__construct(new \RecursiveArrayIterator(\func_get_args()));
        }
    
        public function key()
        {
            return $this->_ordinal;
        }
    
        public function getChildren()
        {
            $current = $this->current();
            if (property_exists($current,'array')) return new \RecursiveArrayIterator(array_values($current->array()));
            throw new \Exception('Shouldn\'t reach here!');
        }
    
        public function hasChildren()
        {
            $current = $this->current();
            return \is_array($current) || $current instanceof \Traversable;
        }
    
        public function next()
        {
            parent::next();
            ++$this->_ordinal;
        }
    
        public function rewind()
        {
            parent::rewind();
            $this->_ordinal = 0;
        }
    
    }
    

    这是测试:

    class TestSource {
      public $array = ['a','b','c'];
    }
    
    foreach (new ContentIterator(new TestSource) as $key => $value) 
        echo "$key => ".json_encode($value)."\n";
    

    测试应产生以下结果:

    0 => "a"
    1 => "b"
    2 => "c"
    

    它实际上会产生这样的结果:

    0 => ["a","b","c"]
    

    如何修复ContentIterator以使其正确执行?

    (是的,我知道我可以使用ArrayIterator或RecursiveArrayIterator在数组中递归。这不是重点。)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jay Bienvenu    6 年前

    显然,PHP 7.0.x中有一个错误导致了这个结果。上面的沙盒表明它在PH 5.6.x和7.1.x下工作。

    推荐文章