Using standard recursion I would do something like this
For an array likePHP Code:function print_list($data $depth = 1) {
echo str_repeat("\t", $depth - 1), "<ul>", PHP_EOL;
foreach ($array as $key => $val) {
if (is_array($val)) {
echo str_repeat("\t", $depth),"<li>", $key, PHP_EOL, print_list($val, $depth + 1), "</li>", PHP_EOL;
}
else {
echo str_repeat("\t", $depth), "<li>",$val,"</li>", PHP_EOL;
}
}
echo str_repeat("\t", $depth - 1),"</ul>", PHP_EOL;
}
And this produces a nice XHTML compliant listPHP Code:$array = array(
"Level 1" => array (
"Level 2" => array(
"Item 1", "Item 2"
),
"Level 2" => array(
"Item 1", "Item 2"
)
)
);
I would like to do this with the SPL's RecursiveIteratorIterator...Code HTML4Strict:<ul> <li>Level 1 <ul> <li>Level 2 <ul> <li>Item 1</li> <li>Item 2</li> </ul> </li> <li>Level 2 <ul> <li>Item 1</li> <li>Item 2</li> </ul> </li> </ul> </li> </ul>
My failed attempt looks like this:
This creates an "</li>" after every item as opposed to my recursive function which recursively prints the child lists before enclosing the "<li>"PHP Code:class RecursiveListIterator extends RecursiveIteratorIterator {
function beginChildren() {
echo str_repeat("\t", $this->getDepth() );
echo "<ul>\n";
}
function endChildren() {
echo str_repeat("\t", $this->getDepth());
echo "</ul>\n";
}
}
$it = new RecursiveListIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST );
foreach($it as $key => $item) {
echo "<li>";
if ($it->getInnerIterator()->hasChildren()) {
echo $key;
}
else {
echo $item;
}
echo "</li>";
}
I feel like the solution is there, and I just need to modify one small thing, but I can't find it.




Bookmarks