Skip to content

Instantly share code, notes, and snippets.

@jakefolio
Last active August 29, 2015 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakefolio/51803873847b6ac40b6e to your computer and use it in GitHub Desktop.
Save jakefolio/51803873847b6ac40b6e to your computer and use it in GitHub Desktop.
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