我发现 PHP 递归迭代器的一个非常奇怪的行为。如果子数组键不是从 0 开始的数字键,它不会迭代子数组。示例如下:
class Foo{
private $id, $children;
public function __construct($id, array $children = array()) {
$this->id = $id;
$this->children = $children;
}
public function getId() {
return $this->id;
}
public function hasChildren()
{
return count($this->children) > 0;
}
public function getChildren()
{
return $this->children;
}
}
class Baz implements RecursiveIterator {
private $position = 0, $children;
public function __construct(Foo $foo) {
$this->children = $foo->getChildren();
}
public function valid()
{
return isset($this->children[$this->position]);
}
public function next()
{
$this->position++;
}
public function current()
{
return $this->children[$this->position];
}
public function rewind()
{
$this->position = 0;
}
public function key()
{
return $this->position;
}
public function hasChildren()
{
return $this->current()->hasChildren();
}
public function getChildren()
{
return new Baz($this->current());
}
}
以下按预期工作:
// Children array keys are numeric and starts from 0. It works.
$foo = new Foo(1, array(
new Foo(2,
array(new Foo(3)))
));
foreach(new RecursiveIteratorIterator(new Baz($foo), RecursiveIteratorIterator::SELF_FIRST) as $j) {
var_dump($j->getId());
}
输出:
int 2
int 3
现在相同的代码,但子键从 2 开始:
// Now array keys starts from 2 and it does not work.
$foo = new Foo(1, array(
2 => new Foo(2,
array(3 => new Foo(3)))
));
foreach(new RecursiveIteratorIterator(new Baz($foo), RecursiveIteratorIterator::SELF_FIRST) as $j) {
var_dump($j->getId());
}
输出为空。
是bug还是什么?PHP 版本为 5.3.27/Windows x86