<?php
$myArray = array(
0 => 'a',
1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
2 => 'b',
3 => array('subA','subB','subC'),
4 => 'c'
); //从这里开始改为类的一个方法
$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator)); function traverseStructure($iterator) {
while ( $iterator -> valid() ) { if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
}
else {
echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
} $iterator -> next();
}
}
?>
基础不够扎实……递归脑筋打结了
traverseStructure($iterator -> getChildren());
===>
$this->traverseStructure($iterator -> getChildren());
ReturnType iterator_apply ( Traversable $iterator , callback $function [, array $args ] )
iterator_apply 就是对迭代器调用函数但写进类我就搞不清关系了,总是这样那样问题
iterator_apply($iterator, array($objname, 'traverseStructure'), array($iterator));
<?php
$myArray = array(
0 => 'a',
1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
2 => 'b',
3 => array('subA','subB','subC'),
4 => 'c'
); class myclass
{
function method($myarray)
{
$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator)); function traverseStructure($iterator) {
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
} else {
echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
}
$iterator -> next();
}
}
?>
$obj=new myclass();
$obj->method($myArray);
还是常规的吧class myclass {
function method($myarray) {
$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, array($this, 'traverseStructure'), array($iterator));
}
function traverseStructure($iterator) {
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
$this->traverseStructure($iterator -> getChildren());
} else {
echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
}
$iterator -> next();
}
}
}