如何通过PHP和mysql建立无限级别的菜单 [英] How to build unlimited level of menu through PHP and mysql

查看:71
本文介绍了如何通过PHP和mysql建立无限级别的菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,为了建立菜单,我使用了类似db的结构

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

要为现有子菜单分配另一个子菜单,我只需将其父ID分配为其父字段的值即可. 父级0表示顶级菜单

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>

我想做的是.

我想检查一个新菜单是否还有其他子菜单

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>";
}

$item的属性和方法仅是示例,我将根据您的需要自行决定实现这些内容,但是我认为它可以传达信息.

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.

这篇关于如何通过PHP和mysql建立无限级别的菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆