Last active
July 25, 2017 17:40
-
-
Save pritchard2751/ec617058434fcb38e9dd to your computer and use it in GitHub Desktop.
Recursive Iteration of a Multidimensional Array Using SPL Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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