Home > php教程 > PHP源码 > body text

php 无限级分类[递归法]

WBOY
Release: 2016-06-08 17:29:48
Original
913 people have browsed it

无限级分类一般是对于商品或站品分类来做的下面我们就来看一下关于使用递归法的算法与代码吧。

<script>ec(2);</script>

// $parent is the parent of the children we want to see

// $level is increased when we go deeper into the tree,

//        used to display a nice indented tree

function display_children($parent, $level) {

    // 获得一个 父节点 $parent 的所有子节点

    $result = mysql_query("

        SELECT name

        FROM tree

        WHERE parent = '" . $parent . "'

        ;"

    );

    // 显示每个子节点

    while ($row = mysql_fetch_array($result)) {

        // 缩进显示节点名称

        echo str_repeat('  ', $level) . $row['name'] . "n";

        //再次调用这个函数显示子节点的子节点

        display_children($row['name'], $level+1);

    }

}

?>


复制代码对整个结构的根节点(Food)使用这个函数就可以打印出整个多级树结构,由于Food是根节点它的父节点是空的,所以这样调用: display_children('',0)。将显示整个树的内容: Food

    Fruit

        Red

            Cherry

        Yellow

            Banana

    Meat

        Beef

        Pork

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!