Loading

php无限分类

无限分类,是指从一个最高分类开始,每个子分类都可以分出自己的若干个子分类,可以一直分下去,称为无限级分类;

比如一棵树,从一根树干开始,分出多个树枝,而这些树枝又分出其他的分支,理论上是可以无限分裂下去的;

再比如,一个家庭可以有若干个子女,我们把这些子女看做是第一级分类。而这些子女,又会各自组建自己的家庭,当他们有了自己的后代,就是第二级分类,如果每个家庭都有一个以上的子女,理论上是可以无限分裂的;

在php中,无限分类的表现形式如下图所示;

我们同过id和pid两个字段来连接父级分类和子集分类,这样就可以找到某一级分类的祖先和它的后代,例如顶级分类>华语歌手>流行歌手>流行男歌手>周杰伦;

通过pid和id来看的话,就是:0-1 , 1-2 , 2-4 , 4-5 , 5-6 (pid在前,id在后);

光是做出数据还不够,我们还需要把数据展示出来,这个时候,我们就需要用到无限分类的递归算法了。

这里先解释一下什么是递归,递归是函数调用自身的一种编程技巧,通过调用自身达到循环的目的。那么问题来了,我们为什么不直接使用循环呢?如果直接使用循环的话,我们就没办法很好的解决参数的问题,特别是当处理一些复杂问题的时候,什么情况下初始化参数,什么情况下累加参数,都会需要额外的思考。不如递归的思路清晰。

看一个简单的递归例子;

function test(&$b=0){
    $b++;
    if($b<10){
        test($b);
    }

    return $b;
}
echo test();

递归作为循环的一种变式,那么它也需要跳出循环的条件,或者是继续循环的条件。这里的&$b是参数传递的一种方式,指引用参数本身,通过&传递的参数,才会不断累积;

回到刚刚的分类:

$host='127.0.0.1';
$db_user='root';
$db_pass='root';
$db_name='chenbk';
$timezone="Asia/Shanghai";
$link=mysqli_connect($host,$db_user,$db_pass,$db_name);
mysqli_query($link,"SET names UTF8");
header("Content-Type: text/html; charset=utf-8");

function tree($link,&$treeList=array(),$pid = 1,$count = 0) {  //$link为数据库连接,&$treeList为输出数组,因为需要累积结果,所以加上引用
    $count+=2;    //count为识别分级深度的标识
    $result = mysqli_query($link,"SELECT * FROM chen_category WHERE parentId={$pid}");
    while ($row=mysqli_fetch_assoc($result)) {
            $row['count'] = $count;
            $row['name'] = str_repeat('&nbsp;', $count).'|-'.$row['name'];  //通过分级深度的标识,来给分类缩进效果
            $treeList[] = $row;   //把查询到的结果存储起来                         
            tree($link,$treeList,$row['id'],$count);  //再次调用自身,这时的pid为上一条数据的id从而找到上一条数据的子分类;
    }
    return $treeList;    //输出结果
}

$values=tree($link);
echo '<select name="parentId" id="">';

foreach ($values as $key => $value) {
    echo '<option value="'.$value['id'].'">'.$value['name'].'</option>';
}

echo '</select>';

这个函数的运行流程为:

1.通过pid=0找到最高分类

2.给它加上层级深度,通过层级深度加上缩进效果,然后把这条数据存起来。

3.再次调用自身,传入2.找出的数据,以及第一级分类的id作为下一级分类的pid;这样,我们每次找到它的子分类,最后就会找到它最小的一级分类;

最终出现的效果是这样的:

我这里把pid的默认值设为了1,所以最高分类没有显示出来;

至于这个算法的排序效果,在于wilhe循环里,调用函数自身的时候,我们第一次查出来的数据是2条,一条华语歌手,一条欧美歌手,但是,在运算的时候,函数是分层调用的,就像多层for循环一样,会等到最内层的循环结束之后,才会依次完成外部的循环。所以我们,在查到华语歌手的时候函数没结束,递归自身又找到了流行歌手,一直到,找到周杰伦之后,才开始处理它上一层的流行女歌手。根据这个流程出来的结果就完成了排序。

 

 

php递归实现无限级分类树

无限级树状图可以说是无限级栏目的一个显著特征,我们接下来就来看看两种不同的写法。

 

一.数据库设计

CREATE TABLE `bg_cate` (
`cate_Id` int(30) unsigned NOT NULL AUTO_INCREMENT,
`cate_ParentId` int(30) unsigned DEFAULT '0',
`cate_Name` varchar(100) NOT NULL,
`cate_Intro` varchar(500) DEFAULT NULL,
`cate_Order` int(30) unsigned DEFAULT '0',
`cate_Icon` varchar(100) DEFAULT NULL,
PRIMARY KEY (`cate_Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=34 ;
--
-- 导出表中的数据 `bg_cate`
--
INSERT INTO `bg_cate` (`cate_Id`, `cate_ParentId`, `cate_Name`, `cate_Intro`, `cate_Order`, `cate_Icon`) VALUES
(4, 0, '往事如风', '记录往事', 0, 'icons/6.gif'),
(5, 0, '水煮三国', '品位三国智慧', 0, 'icons/3.gif'),
(2, 0, '技术学习', '平时学习的一些笔记,欢迎批评指正。', 0, 'icons/18.gif'),
(3, 0, '生活点滴', '记录生活点滴', 0, 'icons/2.gif'),
(6, 0, '栀子花开', '青春无限', 0, 'icons/8.gif'),
(7, 0, '假日休闲', '悠闲、自在', 0, 'icons/24.gif'),
(8, 2, 'html', 'html学习', 0, 'icons/1.gif'),
(9, 2, 'css', 'css学习', 0, 'icons/1.gif'),
(10, 2, 'php', 'php学习', 0, 'icons/18.gif'),
(11, 10, 'php基础知识', 'php基础知识', 0, 'icons/1.gif'),
(12, 10, 'oop', 'oop', 0, 'icons/1.gif'),
(13, 10, 'php安全', '讲述php安全', 0, 'icons/1.gif'),
(14, 10, 'seagull framework', 'seagull framework', 0, 'icons/1.gif'),
(15, 2, 'javascript', 'javascript学习', 0, 'icons/1.gif'),
(16, 2, '设计模式', NULL, 0, 'icons/1.gif'),
(17, 2, '软件工程', '软件工程学习', 0, 'icons/1.gif'),
(18, 3, '厦门生活', '厦门生活', 0, 'icons/8.gif'),
(19, 3, '大学生活', '大学生活', 0, 'icons/8.gif'),
(20, 3, '童年生活', '童年生活', 0, 'icons/15.gif'),
(21, 19, '学习', '学习', 0, 'icons/1.gif'),
(22, 19, '运动', '运动', 0, 'icons/16.gif'),
(23, 19, '旅游', '旅游', 0, 'icons/24.gif'),
(24, 22, '排球', '排球', 0, 'icons/9.gif'),
(25, 22, '篮球', '篮球', 0, 'icons/9.gif'),
(26, 22, '羽毛球', '羽毛球', 0, 'icons/9.gif'),
(27, 22, '乒乓球', '乒乓球', 0, 'icons/9.gif');

二.到数据库取数据,放到数组。

require_once './classes/MyDB.php';
$con = MyDB::singleton();
$sql = <<<SQL
   select * from bg_cate cate
SQL;
$data = $con->getAll($sql);
//print_r($data);

数据库操作我用的是pear类库。
最后的$data的数据格式如下:

Array
(
   [0] => Array
       (
           [cate_Id] => 4
           [cate_ParentId] => 0
           [cate_Name] => 往事如风
           [cate_Intro] => 记录往事
           [cate_Order] => 0
           [cate_Icon] => icons/6.gif
       )
   [1] => Array
       (
           [cate_Id] => 5
           [cate_ParentId] => 0
           [cate_Name] => 水煮三国
           [cate_Intro] => 品位三国智慧
           [cate_Order] => 0
           [cate_Icon] => icons/3.gif
       )

三.把上一步的数据转为树型状的数组
代码如下:

function getTree($data, $pId)
{
$tree = '';
foreach($data as $k => $v)
{
  if($v['cate_ParentId'] == $pId)
  {        //父亲找到儿子
   $v['cate_ParentId'] = getTree($data, $v['cate_Id']);
   $tree[] = $v;
   //unset($data[$k]);
  }
}
return $tree;
}
$tree = getTree($data, 0);

最后输出$tree的数据格式为:

Array
(
   [0] => Array
       (
           [cate_Id] => 4
           [cate_ParentId] =>
           [cate_Name] => 往事如风
           [cate_Intro] => 记录往事
           [cate_Order] => 0
           [cate_Icon] => icons/6.gif
       )
   [1] => Array
       (
           [cate_Id] => 5
           [cate_ParentId] =>
           [cate_Name] => 水煮三国
           [cate_Intro] => 品位三国智慧
           [cate_Order] => 0
           [cate_Icon] => icons/3.gif
       )
   [2] => Array
       (
           [cate_Id] => 2
           [cate_ParentId] => Array
               (
                   [0] => Array
                       (
                           [cate_Id] => 8
                           [cate_ParentId] =>
                           [cate_Name] => html
                           [cate_Intro] => html学习
                           [cate_Order] => 0
                           [cate_Icon] => icons/1.gif
                       )

四.把树型状数组转为html
代码如下:

function procHtml($tree)
{
$html = '';
foreach($tree as $t)
{
  if($t['cate_ParentId'] == '')
  {
   $html .= "<li>{$t['cate_Name']}</li>";
  }
  else
  {
   $html .= "<li>".$t['cate_Name'];
   $html .= procHtml($t['cate_ParentId']);
   $html = $html."</li>";
  }
}
return $html ? '<ul>'.$html.'</ul>' : $html ;
}
echo procHtml($tree);

输出的html的代码格式为:

<ul>
<li>往事如风</li>
<li>水煮三国</li>
<li>技术学习
  <ul>
   <li>html</li>
   <li>css</li>
   <li>php
    <ul>
     <li>php基础知识</li>
     <li>oop</li>
     <li>php安全</li>

五.代码整合

function getTree($data, $pId)
{
$html = '';
foreach($data as $k => $v)
{
  if($v['cate_ParentId'] == $pId)
  {        //父亲找到儿子
   $html .= "<li>".$v['cate_Name'];
   $html .= getTree($data, $v['cate_Id']);
   $html = $html."</li>";
  }
}
return $html ? '<ul>'.$html.'</ul>' : $html ;
}
echo getTree($data, 0);

六.增加CSS样式

884370dfhc28075550cfd&690.jpg


第二种是从开源网站上看到的,非常非常的简介。

<?php
  
function genTree5($items) {
    foreach ($items as $item)
        $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
    return isset($items[0]['son']) ? $items[0]['son'] : array();
}
  
/**
 * 将数据格式化成树形结构
 * @author Xuefen.Tong
 * @param array $items
 * @return array
 */
function genTree9($items) {
    $tree = array(); //格式化好的树
    foreach ($items as $item)
        if (isset($items[$item['pid']]))
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        else
            $tree[] = &$items[$item['id']];
    return $tree;
}
  
$items = array(
    1 => array('id' => 1, 'pid' => 0, 'name' => '江西省'),
    2 => array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'),
    3 => array('id' => 3, 'pid' => 1, 'name' => '南昌市'),
    4 => array('id' => 4, 'pid' => 2, 'name' => '哈尔滨市'),
    5 => array('id' => 5, 'pid' => 2, 'name' => '鸡西市'),
    6 => array('id' => 6, 'pid' => 4, 'name' => '香坊区'),
    7 => array('id' => 7, 'pid' => 4, 'name' => '南岗区'),
    8 => array('id' => 8, 'pid' => 6, 'name' => '和兴路'),
    9 => array('id' => 9, 'pid' => 7, 'name' => '西大直街'),
    10 => array('id' => 10, 'pid' => 8, 'name' => '东北林业大学'),
    11 => array('id' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'),
    12 => array('id' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'),
    13 => array('id' => 13, 'pid' => 1, 'name' => '赣州市'),
    14 => array('id' => 14, 'pid' => 13, 'name' => '赣县'),
    15 => array('id' => 15, 'pid' => 13, 'name' => '于都县'),
    16 => array('id' => 16, 'pid' => 14, 'name' => '茅店镇'),
    17 => array('id' => 17, 'pid' => 14, 'name' => '大田乡'),
    18 => array('id' => 18, 'pid' => 16, 'name' => '义源村'),
    19 => array('id' => 19, 'pid' => 16, 'name' => '上坝村'),
);
echo "<pre>";
print_r(genTree5($items));
print_r(genTree9($items));
  
//后者输出格式,前者类似,只是数组键值不一样,不过不影响数据结构
/*
Array
(
[0] => Array
    (
        [id] => 1
        [pid] => 0
        [name] => 江西省
        [son] => Array
            (
                [0] => Array
                    (
                        [id] => 3
                        [pid] => 1
                        [name] => 南昌市
                    )
  
                [1] => Array
                    (
                        [id] => 13
                        [pid] => 1
                        [name] => 赣州市
                        [son] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 14
                                        [pid] => 13
                                        [name] => 赣县
                                        [son] => Array
                                            (
                                            [0] => Array
                                                (
                                                    [id] => 16
                                                    [pid] => 14
                                                    [name] => 茅店镇
                                                    [son] => Array
                                                        (
                                                        [0] => Array
                                                            (
                                                            [id] => 18
                                                            [pid] => 16
                                                            [name] => 义源村
                                                            )
  
                                                        [1] => Array
                                                            (
                                                            [id] => 19
                                                            [pid] => 16
                                                            [name] => 上坝村
                                                            )
  
                                                        )
  
                                                )
  
                                            [1] => Array
                                                (
                                                    [id] => 17
                                                    [pid] => 14
                                                    [name] => 大田乡
                                                )
  
                                            )
  
                                    )
  
                                [1] => Array
                                    (
                                        [id] => 15
                                        [pid] => 13
                                        [name] => 于都县
                                    )
  
                            )
  
                    )
  
            )
  
    )
  
[1] => Array
    (
        [id] => 2
        [pid] => 0
        [name] => 黑龙江省
        [son] => Array
            (
                [0] => Array
                    (
                        [id] => 4
                        [pid] => 2
                        [name] => 哈尔滨市
                        [son] => Array
                            (
                            [0] => Array
                                (
                                    [id] => 6
                                    [pid] => 4
                                    [name] => 香坊区
                                    [son] => Array
                                        (
                                        [0] => Array
                                            (
                                                [id] => 8
                                                [pid] => 6
                                                [name] => 和兴路
                                                [son] => Array
                                                    (
                                                        [0] => Array
                                                            (
                                                            [id] => 10
                                                            [pid] => 8
                                                            [name] =>
                                                             东北林业大学
                                                            )
  
                                                        [1] => Array
                                                            (
                                                            [id] => 12
                                                            [pid] => 8
                                                            [name] =>
                                                            哈尔滨师范大学
                                                            )
  
                                                    )
  
                                            )
  
                                        )
  
                                )
  
                            [1] => Array
                                (
                                    [id] => 7
                                    [pid] => 4
                                    [name] => 南岗区
                                    [son] => Array
                                        (
                                        [0] => Array
                                            (
                                            [id] => 9
                                            [pid] => 7
                                            [name] => 西大直街
                                            [son] => Array
                                                (
                                                [0] => Array
                                                    (
                                                    [id] => 11
                                                    [pid] => 9
                                                    [name] =>
                                                     哈尔滨工业大学
                                                    )
  
                                                )
  
                                            )
  
                                        )
  
                                )
  
                            )
  
                    )
  
                [1] => Array
                    (
                        [id] => 5
                        [pid] => 2
                        [name] => 鸡西市
                    )
  
            )
  
    )
)*/

php递归实现无限级分类树
作者: default|标签:PHP 递归 无限级树|2017-5-18 18:09
无限级树状图可以说是无限级栏目的一个显著特征,我们接下来就来看看两种不同的写法。

 

一.数据库设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
CREATE TABLE `bg_cate` (
`cate_Id` int(30) unsigned NOT NULL AUTO_INCREMENT,
`cate_ParentId` int(30) unsigned DEFAULT '0',
`cate_Name` varchar(100) NOT NULL,
`cate_Intro` varchar(500) DEFAULT NULL,
`cate_Order` int(30) unsigned DEFAULT '0',
`cate_Icon` varchar(100) DEFAULT NULL,
PRIMARY KEY (`cate_Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=34 ;
--
-- 导出表中的数据 `bg_cate`
--
INSERT INTO `bg_cate` (`cate_Id`, `cate_ParentId`, `cate_Name`, `cate_Intro`, `cate_Order`, `cate_Icon`) VALUES
(4, 0, '往事如风''记录往事', 0, 'icons/6.gif'),
(5, 0, '水煮三国''品位三国智慧', 0, 'icons/3.gif'),
(2, 0, '技术学习''平时学习的一些笔记,欢迎批评指正。', 0, 'icons/18.gif'),
(3, 0, '生活点滴''记录生活点滴', 0, 'icons/2.gif'),
(6, 0, '栀子花开''青春无限', 0, 'icons/8.gif'),
(7, 0, '假日休闲''悠闲、自在', 0, 'icons/24.gif'),
(8, 2, 'html''html学习', 0, 'icons/1.gif'),
(9, 2, 'css''css学习', 0, 'icons/1.gif'),
(10, 2, 'php''php学习', 0, 'icons/18.gif'),
(11, 10, 'php基础知识''php基础知识', 0, 'icons/1.gif'),
(12, 10, 'oop''oop', 0, 'icons/1.gif'),
(13, 10, 'php安全''讲述php安全', 0, 'icons/1.gif'),
(14, 10, 'seagull framework''seagull framework', 0, 'icons/1.gif'),
(15, 2, 'javascript''javascript学习', 0, 'icons/1.gif'),
(16, 2, '设计模式'NULL, 0, 'icons/1.gif'),
(17, 2, '软件工程''软件工程学习', 0, 'icons/1.gif'),
(18, 3, '厦门生活''厦门生活', 0, 'icons/8.gif'),
(19, 3, '大学生活''大学生活', 0, 'icons/8.gif'),
(20, 3, '童年生活''童年生活', 0, 'icons/15.gif'),
(21, 19, '学习''学习', 0, 'icons/1.gif'),
(22, 19, '运动''运动', 0, 'icons/16.gif'),
(23, 19, '旅游''旅游', 0, 'icons/24.gif'),
(24, 22, '排球''排球', 0, 'icons/9.gif'),
(25, 22, '篮球''篮球', 0, 'icons/9.gif'),
(26, 22, '羽毛球''羽毛球', 0, 'icons/9.gif'),
(27, 22, '乒乓球''乒乓球', 0, 'icons/9.gif');

二.到数据库取数据,放到数组。

1
2
3
4
5
6
7
require_once './classes/MyDB.php';
$con = MyDB::singleton();
$sql = <<<SQL
   select from bg_cate cate
SQL;
$data = $con->getAll($sql);
//print_r($data);

数据库操作我用的是pear类库。
最后的$data的数据格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Array
(
   [0] => Array
       (
           [cate_Id] => 4
           [cate_ParentId] => 0
           [cate_Name] => 往事如风
           [cate_Intro] => 记录往事
           [cate_Order] => 0
           [cate_Icon] => icons/6.gif
       )
   [1] => Array
       (
           [cate_Id] => 5
           [cate_ParentId] => 0
           [cate_Name] => 水煮三国
           [cate_Intro] => 品位三国智慧
           [cate_Order] => 0
           [cate_Icon] => icons/3.gif
       )

三.把上一步的数据转为树型状的数组
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getTree($data$pId)
{
$tree '';
foreach($data as $k => $v)
{
  if($v['cate_ParentId'] == $pId)
  {        //父亲找到儿子
   $v['cate_ParentId'] = getTree($data$v['cate_Id']);
   $tree[] = $v;
   //unset($data[$k]);
  }
}
return $tree;
}
$tree = getTree($data, 0);

最后输出$tree的数据格式为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Array
(
   [0] => Array
       (
           [cate_Id] => 4
           [cate_ParentId] =>
           [cate_Name] => 往事如风
           [cate_Intro] => 记录往事
           [cate_Order] => 0
           [cate_Icon] => icons/6.gif
       )
   [1] => Array
       (
           [cate_Id] => 5
           [cate_ParentId] =>
           [cate_Name] => 水煮三国
           [cate_Intro] => 品位三国智慧
           [cate_Order] => 0
           [cate_Icon] => icons/3.gif
       )
   [2] => Array
       (
           [cate_Id] => 2
           [cate_ParentId] => Array
               (
                   [0] => Array
                       (
                           [cate_Id] => 8
                           [cate_ParentId] =>
                           [cate_Name] => html
                           [cate_Intro] => html学习
                           [cate_Order] => 0
                           [cate_Icon] => icons/1.gif
                       )

四.把树型状数组转为html
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function procHtml($tree)
{
$html '';
foreach($tree as $t)
{
  if($t['cate_ParentId'] == '')
  {
   $html .= "<li>{$t['cate_Name']}</li>";
  }
  else
  {
   $html .= "<li>".$t['cate_Name'];
   $html .= procHtml($t['cate_ParentId']);
   $html $html."</li>";
  }
}
return $html '<ul>'.$html.'</ul>' $html ;
}
echo procHtml($tree);

输出的html的代码格式为:

1
2
3
4
5
6
7
8
9
10
11
12
<ul>
<li>往事如风</li>
<li>水煮三国</li>
<li>技术学习
  <ul>
   <li>html</li>
   <li>css</li>
   <li>php
    <ul>
     <li>php基础知识</li>
     <li>oop</li>
     <li>php安全</li>

五.代码整合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getTree($data$pId)
{
$html '';
foreach($data as $k => $v)
{
  if($v['cate_ParentId'] == $pId)
  {        //父亲找到儿子
   $html .= "<li>".$v['cate_Name'];
   $html .= getTree($data$v['cate_Id']);
   $html $html."</li>";
  }
}
return $html '<ul>'.$html.'</ul>' $html ;
}
echo getTree($data, 0);

六.增加CSS样式

884370dfhc28075550cfd&690.jpg


第二种是从开源网站上看到的,非常非常的简介。

posted @ 2018-05-08 13:59  路闻man  阅读(107)  评论(0)    收藏  举报