如何在php中构建一个具有id,parent_id和depth变量的树 [英] How to build a tree in php having id, parent_id and depth variables

查看:406
本文介绍了如何在php中构建一个具有id,parent_id和depth变量的树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从mysql查询中我有id,parent_id和深度变量



深度从0开始



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



我使用CI

解决方案>

首先,你必须编写一个递归函数来读取所有的子元素并输出为和<li>。



正确的形状。您可以使用以下示例代码将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是数据库中的所有行。 / p>

PHP / MySQL构建树菜单


From the mysql query i have id, parent_id and depth variables

depth starts from 0

can you give me an elegant solution or a good link

I am using CI

解决方案

First you have to write a recursive function to read all the child elements and output them as "" and <"li>".

Once you get the proper shape. you can use the following example code to turn li to tree.

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

or

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

You can like below code also

   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 is a recursive function and $array is all the rows from database.

PHP / MySQL build tree menu

这篇关于如何在php中构建一个具有id,parent_id和depth变量的树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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