【问题标题】:How to build a tree in php having id, parent_id and depth variables如何在 php 中构建具有 id、parent_id 和深度变量的树
【发布时间】:2012-07-10 00:05:16
【问题描述】:

从 mysql 查询中我有 id、parent_id 和 depth 变量

深度从0开始

你能给我一个优雅的解决方案或一个好的链接

我正在使用 CI

【问题讨论】:

  • 或者一个关于如何做的小例子,我是菜鸟 :),搜索了谷歌,但没有找到任何使用这个变量的好例子或如此困难的例子

标签: php mysql codeigniter tree


【解决方案1】:

首先你必须编写一个递归函数来读取所有子元素并将它们输出为“”和”。

一旦你得到正确的形状。您可以使用以下示例代码将 li 变为树。

http://www.dynamicdrive.com/dynamicindex1/navigate1.htm

http://odyniec.net/articles/turning-lists-into-trees/

你也可以喜欢下面的代码

   function print_list($array, $parent=0) {
        print "<ul>";
        foreach ($array as $row) {
            if ($row->parent_id == $parent) {
                print "<li>$row->title";
                print_list($array, $row->id);  # recurse
                print "</li>";
        }   }
        print "</ul>";
    }

print_list 是一个递归函数,$array 是数据库中的所有行。

PHP / MySQL build tree menu

【讨论】:

  • 如果第一个父节点不是从 0 开始怎么办
  • 我不知道为什么,但它只渲染第一级深度
  • 我在这里实现了@AjayR 的代码(虽然在 JS 中):gist.github.com/denizozger/9926025
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多