SPL迭代器接口(六)—RecursiveIterator Interface

  RecursiveIterator Interface: 继承自Iterator接口,提供递归访问功能。

  RecursiveIterator与OuterIterator接口一样,继承自Iterator接口。

  RecursiveIterator接口的作用在于提供递归迭代访问功能。这种类型的迭代器接口可以表达为一个树形的数据结构,其中包含了节点元素和叶子元素。目录就是一个典型递归结构。

  RecursiveIterator接口实现代码:

‹?php
//自定义数组迭代器实现递归迭代器接口
class MyRecursiveIterator implements RecursiveIterator 
{ 
    protected $arr;      //存放数据
    protected $index;  //存放当前指针

    public function __construct(array $arr) 
    { 
        $this->arr = $arr; 
    } 
    //判断是否有子元素 
    public function hasChildren() 
    {     
        return is_array($this->arr[$this->index]); 
    }
    //返回子元素的迭代器实例
    public function getChildren() 
    { 
        return new self($this->arr[$this->index]);
    }
    //验证指针是否越界
    public function valid() 
    { 
        return isset($this->arr[$this->index]); 
    }
    //返回当前指针指向数据
    public function current() 
    { 
        return $this->arr[$this->index]; 
    }
    //指针指向下一个元素
    public function next() 
    { 
        $this->index++; 
    } 
    //重置指针
    public function rewind() 
    {     
        $this->index = 0; 
    } 
    //返回当前key值
    public function key() 
    { 
        return $this->index; 
    } 
} 
//递归函数----递归遍历所有元素
function recursive(MyRecursiveIterator $container){
    foreach ($container as $c => $v) {
        if ($container->hasChildren()) { //判断是否有子元素
            echo "第{$c}个元素含有子元素:".PHP_EOL; 
            recursive($container->getChildren()); //递归调用
        } else { 
            echo "第{$c}个元素:$v".PHP_EOL; 
        }
    }
}
//测试数组
$arr = array( 
   0,1,2,array(1,2),array(1,array(1,2,3))
);
//实例化MyRecursiveIterator迭代器
$container = new MyRecursiveIterator($arr);
//调用函数
recursive($container);

  运行结果:

  有点难看,我们让层级之间缩进一下

//递归函数----递归遍历所有元素
function recursive(MyRecursiveIterator $container,$i=0){
    foreach ($container as $c => $v) {
        echo str_repeat("\t",$i);//缩进
        if ($container->hasChildren()) { //判断是否有子元素
            echo "第{$c}个元素含有子元素:".PHP_EOL; 
            recursive($container->getChildren(),$i+1); //递归调用
        } else { 
            echo "第{$c}个元素:$v".PHP_EOL; 
        }
    }
}

  再次运行:

来源:慕课手记 https://www.imooc.com/article/17908

转载请注明出处:https://www.onexin.net/spl-recursiveiterator-interface/

相关文章:

1、SPL迭代器接口(五)—OuterIterator Interface
https://www.onexin.net/spl-outeriterator-interface/

2、SPL迭代器接口(四)—IteratorAggregate Interface
https://www.onexin.net/spl-iteratoraggregate-interface/

3、SPL迭代器接口(三)—SeekableIterator Interface
https://www.onexin.net/spl-seekableiterator-interface/

4、SPL迭代器接口(二)—Iterator Interface
https://www.onexin.net/spl-iterator-interface/

5、SPL迭代器接口(一)—Traversable Interface
https://www.onexin.net/spl-traversable-interface/

Leave a Reply