接口
在线手册:中文 英文
PHP手册

The RecursiveIterator interface

(PHP 5 >= 5.1.0)

简介

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

接口摘要

RecursiveIterator extends Iterator {
/* 方法 */
public RecursiveIterator getChildren ( void )
public bool hasChildren ( void )
/* 继承的方法 */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Table of Contents


接口
在线手册:中文 英文
PHP手册
PHP手册 - N: The RecursiveIterator interface

用户评论:

andresdzphp at php dot net (04-Oct-2011 08:43)

RecursiveIterator example:

<?php

class MyRecursiveIterator implements RecursiveIterator
{
    private
$_data;
    private
$_position = 0;
   
    public function
__construct(array $data) {
       
$this->_data = $data;
    }
   
    public function
valid() {
        return isset(
$this->_data[$this->_position]);
    }
   
    public function
hasChildren() {
        return
is_array($this->_data[$this->_position]);
    }
   
    public function
next() {
       
$this->_position++;
    }
   
    public function
current() {
        return
$this->_data[$this->_position];
    }
   
    public function
getChildren() {
        echo
'<pre>';
       
print_r($this->_data[$this->_position]);
        echo
'</pre>';
    }
   
    public function
rewind() {
       
$this->_position = 0;
    }
   
    public function
key() {
        return
$this->_position;
    }
}

$arr = array(0, 1, 2, 3, 4, 5 => array(10, 20, 30), 6, 7, 8, 9 => array(1, 2, 3));
$mri = new MyRecursiveIterator($arr);

foreach (
$mri as $c => $v) {
    if (
$mri->hasChildren()) {
        echo
"$c has children: <br />";
       
$mri->getChildren();
    } else {
        echo
"$v <br />";
    }

}
?>

Result:

0
1
2
3
4
5 has children:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
6
7
8
9 has children:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)