开发者

RecursiveArrayIterator current array

I am trying to get the whole current array and I don't think I have gone the right way about it as I get an Undefined index error sometimes.

    $iterator = new RecursiveIteratorIterator开发者_高级运维(new RecursiveArrayIterator($comments_array), RecursiveIteratorIterator::SELF_FIRST);
    while ($iterator->valid()) {
        if ($iterator->hasChildren()) {
            $row = $iterator->getChildren();
            $depth = $iterator->getDepth();
            echo $row['User_ID'] . "<br>";
        }
        $iterator->next();
    }

I know you can do foreach ($iterator->getChildren() as $key => $value) but that doesn't help me as I want the whole array.

Hope this makes sense?!


I often approach this kind of task with a filtering iterator, rather than having some crazy nested set of if blocks. Oftentimes, tasks like these can be abstracted out to something more generic--useful for more than just this one array/loop--and this is the approach I've taken here.

Because of that, the answer below is not the easiest, quickest or smallest change to your code to get the job done. However, it might come in useful elsewhere for yourself or anyone else wanting to do something similar with any kind of recursive iterator.


So, the task boils down to how can I get only the parents of an iterator (or array) without the parents of parents? One way is with a filtering iterator like below:

class FirstParentIterator extends FilterIterator {
    public function __construct(RecursiveIterator $iterator) {
        parent::__construct(
            new RecursiveIteratorIterator(
                new ParentIterator($iterator),
                RecursiveIteratorIterator::SELF_FIRST
            )
        );
    }
    public function accept() {
        // Only accept immediate parents of leaf elements
        return $this->hasChildren() && ! $this->getChildren()->hasChildren();
    }
}

Putting such a filter to some use makes your original loop much tidier:

$iterator = new FirstParentIterator(new RecursiveArrayIterator($comments_array));
foreach ($iterator as $row) {
    echo $row['User_ID'] . "<br>";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜