使用递归获取无限级树分类

创建一个分类表

drop table if exists category;
create table category(
id int unsigned auto_increment primary key comment 'id',
name varchar(50) not null comment '类别名称',
sort_order int not null default 50 comment '排序名称',
parentid int unsigned not null comment '父级ID'
) engine=innodb charset=utf8;

添加数据

insert into category values (1,'图像、音像、数字商品',default,0);
insert into category values (2,'家用电器',default,0);
insert into category values (3,'手机、数码',default,0);
insert into category values (4,'电子书',default,1);
insert into category values (5,'数字音乐',default,1);
insert into category values (6,'励志与成功',default,4);
insert into category values (7,'文学',default,4);
insert into category values (8,'大家电',default,2);
insert into category values (9,'图像、音像、数字商品',default,0);

无限级树状图可以说是无限级栏目的一个显著特征,递归函数是大家经常会使用的,它在函数体内部直接或者间接的自己调用自己,必须在调用自身前有条件判断,否则无限无限调用下去。前面的章节什么是php递归函数以及介绍一个简单的实例来说明。

这一节我们来介绍php如何实现递归函数的几种方法。这里列出了三种基本方式。理解其原来需要一定的基础知识水平,包括对全局变量,引用,静态变量的理解,也需对他们的作用范围有所理解。递归函数也是解决无限级分类的一个很好地技巧。

<?php
/**
 * Created by PhpStorm.
 * User: nobita
 * Date: 8/21
 * Time: 14:06
 */
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<?php
    $link = mysqli_connect('127.0.0.1','root','root','nobita');
    $sql = 'select * from category order by sort_order';
    $res = mysqli_query($link,$sql);
    $array = array();
    while ($rows = mysqli_fetch_assoc($res)){
        $array[]=$rows;
    }
    function createTree($list,$parentid=0,$deep=0){
        static $tree = array();
        foreach($list as $rows){
            if ($rows['parentid'] == $parentid){
                $rows['deep'] = $deep;
                $tree[] = $rows;
                createTree($list,$rows['id'],$deep+1);
            }
        }
        return $tree;
    }
    echo '<pre>';
    $temp = createTree($array);
    foreach ($temp as $rows){
        echo str_repeat(' ',$rows['deep']).$rows['name'],'<br>';
    }
?>
<?php
    mysqli_close($link);
?>
</body>
</html>
Comments: 0

「人生在世,留句话给我吧」

提交评论