PHP MySql:打印树 - 父子复选框

时间:2014-05-05 19:30:18

标签: php jquery mysql css3

我有这个MySql表用于放置多个新闻类别(父/子):

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

现在我需要将其打印到jQueryCSS3 html CheckBOX,如下所示:

NOTE: This is Simple Example for HTML treeview.

enter image description here

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']);
     } 

我需要为每个根猫打印<ul><li></li></ul>并为每个父类别打印<ul><li><ul><li></li></ul></li></ul>

如何使用PHP/MySQL创建/打印此内容:

1 个答案:

答案 0 :(得分:1)

使用递归!注意:下面的代码对于循环图是不安全的(节点可能不是它们自己的祖先)!

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