PHP MySql: Print Tree - Parent Child Checkbox

纵然是瞬间 提交于 2019-12-31 04:03:49

问题


I have This MySql table for put multiple news categories(parent/child) :

ID  |   NAME    |  PARENTID  | DESC |
 1  |   LINUX   |     0      | NULL |
 2  |   DEBIAN  |     1      | NULL |
 3  |   SLAX    |     1      | NULL |
 4  | SLAXLIVE  |     3      | NULL |
 5  |  SWFLIVE  |     3      | NULL |

Now I need to print this to jQuery and CSS3 html CheckBOX like this :

NOTE: This is Simple Example for HTML treeview.

HTML:

<ul>
        <li>    <a href="#">Parent</a>

            <ul>
                <li>    <a href="#">Child</a>

                    <ul>
                        <li>    <<a href="#">Grand Child</a>

                        </li>
                    </ul>
                </li>
                <li>    <a href="#">Child</a>

                    <ul>
                        <li><a href="#">Grand Child</a>
                        </li>
                        <li>    <a href="#">Grand Child</a>

                            <ul>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                                <li>    <a href="#">Great Grand Child</a>

                                </li>
                            </ul>
                        </li>
                        <li><a href="#">Grand Child</a>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>

PHP:

$result = mysql_query("SELECT id, name, parent FROM " . NEWS_CATS . " ORDER BY name");
    $items = array();
     while($row = mysql_fetch_array($result))
         { $items[] = array('id' => $row['id'], 'label' => $row['name'], 'parent' => $row['parent']);
     } 

i need to print <ul><li></li></ul> for each root cat and print <ul><li><ul><li></li></ul></li></ul> for each parent category.

how do i can create/print this using PHP/MySQL:


回答1:


Use recursion! Note: the code below is not safe for cyclic graphs (nodes may not be ancestors of themselves)!

printChildren($items,0);
function printChildren(array $items, $parentId){
    foreach($items as $item){
        if($item['parent']==$parentId){
            print '<li>';
            print $item['label']; //or whatever you want about the current node
            print '<ul>';
            printChildren($items, $item['id']);
            print '</ul></li>';
        }
    }
}


来源:https://stackoverflow.com/questions/23480266/php-mysql-print-tree-parent-child-checkbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!