我的博客| Blog
- ·微信小程序错误:VM564:...
- ·mongodb3.2设置密码...
- ·单行滚动代码-单行滚动效果
- ·自己动手制作图形字体,以便于...
- ·MySQL无限级分类PHP按...
- ·Windows下的Apach...
- ·如何将网站上的文章分享到微信...
- ·PHP实现自动获取本月第几个...
联系我| Contact Me
- 电话:18681257080
- QQ:271538869
- 邮编:518020
- 信箱:service@08321.org
- 地址:四川省内江市资中县
诚信稳健,和谐共赢
- 以诚信为立世之本,在稳健的基础上,不断寻求创新与突破。
- 以务实严谨、精微细致的专业精神,为客户做最优质的策划,实现效果最大化。
成功,依稀可见
- 成功是什么?
- 做成一件达到目的的事,你就获得了一个小成功,小成功可以累积成更大的成功。每一人都有成功的机会。所以:成功,依稀可见!
我的博客
MySQL无限级分类PHP按层次阶梯识别
来源:本站编辑 发布日期:2015-11-25 已有 人浏览过此信息
Mysql数据表结构如下:
+----+--------------+----------+
| id | dname | parentid |
+----+--------------+----------+
| 1 | 顶级分类 | 0
| 2 | 一级分类 | 1
| 3 | 一级分类 | 1
| 4 | 二级分类 | 3
| 5 | 二级分类 | 3
| 6 | 一级分类 | 1
| 7 | 一级分类 | 1
| 8 | 二级分类 | 6
| 9 | 二级分类 | 6
+----+--------------+----------+
函数定义:
<?php
//$pid为父类ID, $id为默认选中状态ID
function department($pid=0,$id=0){
global $conn;
global $lv;$lv++; //函数执行 递归增加 层级增加
$dp=mysql_query("select * from department where parentid=$pid order by id asc",$conn);
$txt='';
while($d=mysql_fetch_array($dp)){
if($id==$d[0]){$sel=' selected="selected"';}else{$sel='';}
$txt.= '<option value="'.$d[0].'"'.$sel.'>';
for($j=1;$j< $lv;$j++){$txt.=' ';} //根据层级添加空格,展现效果即可体现出层级关系
$txt.= $d['dname'];
$txt.= '</option>';
$txt.=department($d[0],$id); //函数递归调用
}
mysql_free_result($dp);
$lv--; //递归回来后层级自减
return $txt;
}
?>
调用方法:
<select name="department" size="1">
<?php
$lv=0 //层次初始化
echo department(0); //调用函数,参数0为默认从顶级分类遍历 parentid=0
?>
</select>
+----+--------------+----------+
| id | dname | parentid |
+----+--------------+----------+
| 1 | 顶级分类 | 0
| 2 | 一级分类 | 1
| 3 | 一级分类 | 1
| 4 | 二级分类 | 3
| 5 | 二级分类 | 3
| 6 | 一级分类 | 1
| 7 | 一级分类 | 1
| 8 | 二级分类 | 6
| 9 | 二级分类 | 6
+----+--------------+----------+
函数定义:
<?php
//$pid为父类ID, $id为默认选中状态ID
function department($pid=0,$id=0){
global $conn;
global $lv;$lv++; //函数执行 递归增加 层级增加
$dp=mysql_query("select * from department where parentid=$pid order by id asc",$conn);
$txt='';
while($d=mysql_fetch_array($dp)){
if($id==$d[0]){$sel=' selected="selected"';}else{$sel='';}
$txt.= '<option value="'.$d[0].'"'.$sel.'>';
for($j=1;$j< $lv;$j++){$txt.=' ';} //根据层级添加空格,展现效果即可体现出层级关系
$txt.= $d['dname'];
$txt.= '</option>';
$txt.=department($d[0],$id); //函数递归调用
}
mysql_free_result($dp);
$lv--; //递归回来后层级自减
return $txt;
}
?>
调用方法:
<select name="department" size="1">
<?php
$lv=0 //层次初始化
echo department(0); //调用函数,参数0为默认从顶级分类遍历 parentid=0
?>
</select>