What you assume is pointing in the right direction, there is a problem with the hasChildren()
method you have. Compare it with the valid()
and with the current()
method, you then probably already see that it will always return true.
Because as long as there is a current()
, hasChildren()
returns true:
public function current()
{
return $this->children[$this->position];
}
and:
public function hasChildren()
{
return !empty($this->children[$this->position]);
}
Instead you want to test if the current element has children or not:
public function hasChildren()
{
return !empty($this->current()->children);
}
The slight difference that will give you your output:
Subitem 1
Subsubitem 1
Enough....
Item 2
Item 3
By always returning TRUE
for hasChildren()
, the RecursiveIteratorIterator
is unable to detect any leaves. By concept of a tree, this is not possible but in a traversal process - as you demonstrated with your "bug" - clearly possible :)
See as well (if I may):