Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Navigation Iterator (Fun With Iterators)
<?php
/**
* RecursiveNavigationIterator
*/
class RecursiveNavigationIterator extends RecursiveIteratorIterator
{
public $openTag = "<ul>\n";
public $closeTag = "</ul>\n";
public function beginIteration()
{
echo str_repeat("\t", $this->getDepth());
echo $this->openTag;
}
public function endIteration()
{
echo str_repeat("\t", $this->getDepth());
echo $this->closeTag;
}
public function beginChildren()
{
echo str_repeat("\t", $this->getDepth());
echo $this->openTag;
}
public function endChildren()
{
echo str_repeat("\t", $this->getDepth());
echo $this->closeTag;
}
public function current()
{
if ($this->getInnerIterator()->hasChildren()) {
return $this->key();
}
return $this->getInnerIterator()->current();
}
}
$it = new RecursiveArrayIterator([
'Home',
'About' => ['Careers', 'Contact'],
'Location',
'FAQ',
]);
$navIt = new RecursiveNavigationIterator($it, RecursiveIteratorIterator::SELF_FIRST);
foreach ($navIt as $navItem) {
echo str_repeat("\t", $navIt->getDepth() + 1);
echo "<li>{$navItem}</li>\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.