PHP/MySQL Navigation Menu

前端 未结 2 1052
后悔当初
后悔当初 2021-01-27 13:04

I\'m trying to create a function for a hierarchical navigational menu bar.

I want to be able to have something like this...

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 13:10

    I think your problem could have something to do with the fact that your function is recursive, but the string you're building gets reset at the top of your function each time, instead of being passed into the function again. Also, I don't see anywhere that sub will get set back to zero for your final iteration. Additionally, it seems like you shouldn't need to query for each individual row. It would be more effective to query once and build the whole menu. I think the recursion can be ditched. Also, I would recommend storing a "sub" flag in your data, instead of using some hard to understand php logic as to whether or not a given row is a sub menu. I made modifications based of these concepts, no idea if it works or not though since I don't have/want to create the data to test it:

    function build_navbar()
    {
        global $db;
        //first things first, i'd recommend putting a "sub" flag in your database. This example will use it.
    
        //start off by getting all of the rows. No need for recursion.
        $query = $db->simple_select("navbar", "*", "1", array("order_by" => "disporder"));
        $menu_build = "
      \n"; //keep track of what level we're at $level = 1; while($menu = $db->fetch_array($query)) { //get sub from data $sub = $menu['sub'] //we need to go back to root level if($sub == 0 && $level == 2){ $level--; $menu_build .= "
  • \n"; } else $menu_build .= "\n"; //we need to go up one level if($sub == 1 && $level == 1) { $level++; $menu_build .= "
    • \n"; } else $menu_build .= "
    • "; //always print out a link $menu_build .= "".$menu['title']."\n"; } $menu_build .= "
    \n"; return $menu_build; }

提交回复
热议问题