我一直在使用 RecursiveArrayIterators 将嵌套对象作为树处理。下面的代码让我很困扰,因为结果只返回了我期望的一些值。主要是,根节点似乎永远不会被迭代。我有一种感觉,我只是盯着它看了太久,但想确保我在正确的轨道上。
class Container extends \RecursiveArrayIterator
{
protected $_alias;
public function __construct( $alias = null )
{
if( is_null( $alias ) )
{
$alias = uniqid( 'block_' );
}
$this->_alias = $alias;
}
public function getAlias()
{
return $this->_alias;
}
}
try
{
$root = new Container( 'root_level' );
$block = new Container( 'first_level' );
$child = new Container( 'second_level' );
$child_of_child_a = new Container( 'third_level_a' );
$child_of_child_b = new Container( 'third_level_b' );
$child->append( $child_of_child_a );
$child->append( $child_of_child_b );
$child_of_child_a->append( new Container );
$child_of_child_a->append( new Container );
$block->append( $child );
$root->append( $block );
$storage = new \RecursiveIteratorIterator( $root, RecursiveIteratorIterator::SELF_FIRST );
foreach( $storage as $key => $value )
{
print_r( str_repeat( ' ', $storage->getDepth() * 4 ) . $value->getAlias() . PHP_EOL );
}
}
catch( \Exception $e )
{
var_dump( $e->getMessage() );
}
结果是...
first_level
second_level
third_level_a
block_51f98b779c107
block_51f98b779c124
third_level_b
根节点在哪里?
回答
斯文的回答让我过度劳累的大脑无法正确处理这个问题。这是我最后一点成功的代码,以防其他人尝试类似的事情。
class OuterContainer extends \ArrayIterator
{
}
class Container extends \ArrayIterator
{
protected $_alias;
public function __construct( $alias = null )
{
if( is_null( $alias ) )
{
$alias = uniqid( 'container_' );
}
$this->_alias = $alias;
}
public function getAlias()
{
return $this->_alias;
}
}
try
{
$c1 = new Container( 'Base' );
$c1_c1 = new Container( 'Base > 1st Child' );
$c1_c2 = new Container( 'Base > 2nd Child' );
$c1_c1_c1 = new Container( 'Base > 1st Child > 1st Child' );
$c1_c1->append( $c1_c1_c1 );
$c1->append( $c1_c1 );
$c1->append( $c1_c2 );
$outer_container = new OuterContainer;
$outer_container->append( $c1 );
$storage = new \RecursiveIteratorIterator( new \RecursiveArrayIterator( $outer_container ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $storage as $key => $value )
{
print_r( $value->getAlias() . PHP_EOL );
}
}
catch( \Exception $e )
{
var_dump( $e->getMessage() );
}