Skip to content

Instantly share code, notes, and snippets.

@pritchard2751
Last active July 25, 2017 17:40
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 pritchard2751/ec617058434fcb38e9dd to your computer and use it in GitHub Desktop.
Save pritchard2751/ec617058434fcb38e9dd to your computer and use it in GitHub Desktop.
Recursive Iteration of a Multidimensional Array Using SPL Iterators
<?php
$nav_menu = array("Level 1" => array("Level 1 child (a)", "Level 1 child (b)"),
"Level 2" => array("Level 2 child (a)" =>
array("Level 2.1 child (a)" =>
array("Level 2.2 child (a)"),
"Level 2.1 Child (b)"
),
"Level 2 child (b)"
),
"Level 3"
);
//print_r($nav_menu);
$rai = new RecursiveArrayIterator($nav_menu);
$rii = new RecursiveIteratorIterator($rai, RecursiveIteratorIterator::SELF_FIRST);
$str ="<ul>";
foreach($rii as $key => $value ) {
echo "<b>Depth: </b>" . $rii->getDepth() ."<br>";
echo "<b>Key: </b>" . $key . "<br>";
echo "<b>Value: </b>"; print_r($value); echo "<br>";
echo "*************************<br>";
if($rii->callHasChildren()){
$str .= "<li>" . $rii -> key();
$str .= "<ul>";
//Find out how many children the current parent has
$children = $rii->callGetChildren();
$childrenCount = $children->count();
}
else {
$str.= "<li>" . $rii -> current() . "</li>";
//Close the unordered list if the current child is the final child
if($rii -> key() == $childrenCount-1) $str.= "</ul>";
}
}
echo($str);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment