Unlimited Children Loop in PHP

Children loops are pesky little annoyances when it comes to remembering exactly how to do it. This time, after searching for the right way to do it, I figured it out and never wanted to lose it again. This is why I posted it on here, so it is easy to find next time.

The code is pretty short and simple, it pulls an unlimited amount of children’s children from the database printing them inside an ordered list for appropriate formatting as this ia for a drop-down menu. It can easily be adapted for any other purpose though. Check out the code below.

<?php

function display_children($parent) {

// retrieve all children of $parent
$m = ‘SELECT * FROM menus WHERE parentid=”‘.$parent.'”‘;
$result = mysql_query($m);

// display each child
echo “<ul id=’nav’ class=’dropdown dropdown-vertical dropdown-vertical-rtl’ style=’width:150px’>”;

while ($row = mysql_fetch_array($result)) {

//echo $row[‘parentid’].”<br>”;
// indent and display the title of this child
//echo str_repeat(‘  ‘,$level).$row[‘id’].”<br>n”;

echo “<li font=’color=#000000′><a href=”>”.$row[‘heading’].”</a></li>”;

// call this function again to display this child’s children
display_children($row[‘id’]);

}
echo “</ul>”;
}

display_children(0); //first time passed as 0 to get all top parents

?>

Leave A Comment

Your email address will not be published. Required fields are marked *

Timber Web Design
2600A E. Seltice #274
Post Falls, ID 83854

509-954-0795

Timber Web Design © 2023. All Rights Reserved.