PHP/MySQL 构建树形菜单 [英] PHP / MySQL build tree menu

查看:25
本文介绍了PHP/MySQL 构建树形菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PHP 和 MySQL 从我的数据库构建一个无序的列表菜单树.

I am trying to build an un-oredered list menu tree from my database in PHP and MySQL.

我有一个从数据库返回的页面对象数组.每个页面对象都有 parent_id 属性,如果它没有父对象,则该属性设置为 null.下面是页面对象的样子:

I have an array of page objects I am returning from the db. Each page object has parent_id attribute, which is set to null if it doesn't have a parent. Here's what the page objects look like:

page object
  id
  title
  parent_id

如果可能的话,我不想递归执行,只访问数据库一次,因为我将在几乎每个请求上构建菜单.我想创建一个函数,我可以将我的对象数组传递给它,它将返回 html 列表.

If possible I would like to not do it recursively and only hit the database once, since I am going to be building the menu on almost every request. I want to create a function that I can just pass my array of objects to and it will return the html list.

推荐答案

我喜欢 @mario 的解决方案,并通过防止多余的

    对其进行了改进.我只建议对您的 SQL 查询执行 ORDER BY 以按照您想要的顺序获取菜单(甚至可能建议将权重/序列列添加到架构中.

    I like @mario's solution, and have improved on it with the prevention of the excess <ul>. I would just recommend doing an ORDER BY on your SQL query to get the menu in the order you want (might even recommend a weight/sequence column be added to the schema.

    数据设置:

    $menu = array( // Presumed to have been coming from a SQL SELECT, populated for demo.
      array('id'=>1,'title'=>'Menu 1',          'parent_id'=>null),
      array('id'=>2,'title'=>'Sub 1.1',         'parent_id'=>1),
      array('id'=>3,'title'=>'Sub 1.2',         'parent_id'=>1),
      array('id'=>4,'title'=>'Sub 1.3',         'parent_id'=>1),
      array('id'=>5,'title'=>'Menu 2',          'parent_id'=>null),
      array('id'=>6,'title'=>'Sub 2.1',         'parent_id'=>5),
      array('id'=>7,'title'=>'Sub Sub 2.1.1',   'parent_id'=>6),
      array('id'=>8,'title'=>'Sub 2.2',         'parent_id'=>5),
      array('id'=>9,'title'=>'Menu 3',          'parent_id'=>null),
    );
    

    处理:

    function has_children($rows,$id) {
      foreach ($rows as $row) {
        if ($row['parent_id'] == $id)
          return true;
      }
      return false;
    }
    function build_menu($rows,$parent=0)
    {  
      $result = "<ul>";
      foreach ($rows as $row)
      {
        if ($row['parent_id'] == $parent){
          $result.= "<li>{$row['title']}";
          if (has_children($rows,$row['id']))
            $result.= build_menu($rows,$row['id']);
          $result.= "</li>";
        }
      }
      $result.= "</ul>";
    
      return $result;
    }
    echo build_menu($menu);
    

    输出:

    <ul>
      <li>Menu 1<ul>
        <li>Sub 1.1</li>
        <li>Sub 1.2</li>
        <li>Sub 1.3</li>
      </ul></li>
      <li>Menu 2<ul>
        <li>Sub 2.1<ul>
          <li>Sub Sub 2.1.1</li>
        </ul></li>
        <li>Sub 2.2</li>
      </ul></li>
      <li>Menu 3</li>
    </ul>

    这篇关于PHP/MySQL 构建树形菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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