Skip to content Skip to sidebar Skip to footer

Help With Php Recursive Navigation List Menu

I am trying to add a dynamic recursive navigation list menu to a site of am working on. The scenerio is that the menu has 2 levels related by a parentid(preid). My issue is that I

Solution 1:

In a nested list, sub-lists will always be contained within a list element-- that's what makes them nested. You can print a full list in just one function using this format (in generic code, but you should get the basic idea):

functionget_list($parent) {
    $children = query('SELECT * FROM table WHERE parent_id = '.$parent);
    $items = array();
    while($row = fetch_assoc($children)) {
        $items[] = '<li>'.$row['name'].get_list($row['id']).'</li>';
    }
    if(count($items)) {
        return'<ul>'.implode('', $items).'</ul>';
    } else {
        return'';
    }
}

And this will give you a list structured properly as:

<ul>
    <li>Item 1</li>
    <li>Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
</ul>

Solution 2:

All though this question is not the exact same as the question I posted 2 days ago, here is the result of what I was attempting to do with folders rather than a DB. The following will traverse the directory and all sub directories of the specified $path and spits out the results in a nested un-ordered list upon completion of running the script. Hope it helps.

<?phpfunctionreadDirs($path){
    $dirHandle = opendir($path);
    echo"<ul>";
    while ($item = readdir($dirHandle)) {
        $newPath = $path . "/" . $item;

        if (is_dir($newPath) && $item != '.' && $item != '..') {
            echo"<li><a href='$newPath'>$item</a>";
            readDirs($newPath);
        }
    }
    echo"</li></ul>";
}
$path = "./galleries";
readDirs($path);

?>

Post a Comment for "Help With Php Recursive Navigation List Menu"