php+mysql不用递归实现的无限级分类实例(非递归)
要实现无限级分类,递归一般是第一个也是最容易想到的,但是递归一般被认为占用资源的方法,所以很多系统是不考虑使用递归的
本文还是通过数据库的设计,用一句sql语句实现
数据库字段大概如下:
id编号 fid父分类编号 class_name分类名 path分类路径,以id为节点,组成类似,1,2,3,4,这样的字符串
可以假设有如下的数据:
idfidclass_namepath 1 0 分类1, 1, 2 0 分类2, 2, 3 1 分类1-1, 1,3, 4 1 分类1-2, 1,4, 5 2 分类2-1, 2,5, 6 4 分类1-2-1,1,4,6,
无限级分类操作代码:
<?php $sql=”SELECT*FROMtreeorderbypath”; $result=$nbs->Query($sql); while($rows=$nbs->fetch_array($result)){ if(substr_count($rows['path'],',')>2){ for($i=0;$i<(substr_count($rows['path'],',')-2);$i++) echo‘‘; } echo$rows['class_name'].'<br>'; } ?> $conn=mysql_connect('localhost','root','root'); mysql_select_db('wanggou123',$conn); mysql_query('setnamesUTF8'); $sql="selectid,concat(catpath,'-',id)asabspath,namefromcategoryorderbyabspath"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)){ /** *第一种展示方法 */ /*$space=str_repeat(' ',count(explode('-',$row['abspath']))-1); echo$space.$row['name'].' ';*/ /** 第二种展示方法 */ $space=str_repeat('——',count(explode('-',$row['abspath']))-1); $option.=''.$space.$row['name'].'<Br>'; } echo$option; exit(); echo'<selectname="opt">'.$option.'</select>';
其中$nbs是数据库操作类,此方法简单明了!