使用RecursiveIteratorIterator迭代作为属性值的数组

时间:2018-12-15 19:24:49

标签: php

我正在开发一个内容迭代器,该迭代器应递归到数组中并将每个值作为单独的迭代返回。这是我的课程的摘要版本:

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 个答案:

答案 0 :(得分:0)

显然,PHP 7.0.x中存在一个导致此结果的错误。沙盒上方显示了它可以在PH 5.6.x和7.1.x中工作。