且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过PHP和mysql构建无限级别的菜单

更新时间:2023-01-17 13:06:33

您需要为此使用递归函数.从技术上讲,有几种方法可以做到,但递归确实是这里的***选择.

以下是其工作原理的基本要点:

function drawMenu ($listOfItems) {echo "
    ";foreach ($listOfItems 作为 $item) {echo "
  • ".$item->name;如果 ($item->hasChildren()) {drawMenu($item->getChildren());//这里是递归}echo "</li>";}echo "</ul>";}

$item 的属性和方法只是示例,我会根据需要由您来实现这些,但我认为它可以传达信息.

Well, to build my menu my menu I use a db similar structure like this

  2  Services                  0
  3  Photo Gallery             0
  4  Home                      0
  5  Feedback                  0
  6  FAQs                      0
  7  News & Events             0
  8  Testimonials              0
 81  FACN                      0
 83  Organisation Structure   81
 84  Constitution             81
 85  Council                  81
 86  IFAWPCA                  81
 87  Services                 81
 88  Publications             81

To assign another submenu for existing submenu I simply assign its parent's id as its value of parent field. parent 0 means top menu

now there is not problem while creating submenu inside another submenu

now this is way I fetch the submenu for the top menu

<ul class="topmenu">
    <? $list = $obj -> childmenu($parentid); 
        //this list contains the array of submenu under $parendid
        foreach($list as $menu) {
            extract($menu);
            echo '<li><a href="#">'.$name.'</a></li>';
        }
    ?>
</ul>

What I want to do is.

I want to check if a new menu has other child menu

and I want to keep on checking until it searches every child menu that is available

and I want to display its child menu inside its particular list item like this

<ul>       
       <li><a href="#">Home</a>
        <ul class="submenu">
           ........ <!-- Its sub menu -->
           </ul>
       </li>
</ul>

You need to use recursive functions for this. Technically, there's a few ways to do it, but recursion is really the best option here.

Here's the basic gist of how it would work:

function drawMenu ($listOfItems) {
    echo "<ul>";
    foreach ($listOfItems as $item) {
        echo "<li>" . $item->name;
        if ($item->hasChildren()) {
            drawMenu($item->getChildren()); // here is the recursion
        }
        echo "</li>";
    }
    echo "</ul>";
}

The properties and methods of $item are just examples, and I'll leave it up to you to implement these however you need to, but I think it gets the message across.