要实现无限级分类,递归一般是第一个也是最容易想到的,但是递归一般被认为占用资源的方法,所以很多系统是不考虑使用递归的
本文还是通过数据库的设计,用一句sql语句实现
数据库字段大概如下:
可以假设有如下的数据:
无限级分类操作代码:
<?php
$sql=”SELECT * FROM tree order by path”;
$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 ( ‘set names UTF8‘ );
$sql = "select id,concat(catpath,‘-‘,id) as abspath,name from category order by abspath";
$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 ‘<select name="opt">‘ . $option . ‘</select>‘;
其中$nbs是数据库操作类,此方法简单明了!
原文:http://www.jb51.net/article/51988.htm