一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php+mysql无限级分类程序代码

时间:2013-03-02 编辑:简简单单 来源:一聚教程网

表结构:id字段为分类标识,name字段为分类名,father_id字段为所属父分类的id,path字段为分类路径(储存该分

类祖先的集合),isdir判断是否是目录(1为是,0为否)。

例1

 代码如下 复制代码

//$count为分类等级
sort_list($str,$fatherid,$count)
{
$rs = $this->sql->re_datas("select * from sort where father_id = fatherid");
$num = $this->sql->sql_numrows();
$i=0;
$n = 1;
while(isset($rs[$i]))
{
$name = "";
for($n = 1 ; $n < $count ; $n++)
{
$name.="│ ";
}
if($i+1==$num)
{
$name.="└─".$rs[$i][name];
}
else
{
$name.="├─".$rs[$i][name];
}
if($rs[$i][isdir])
{
$str.="".$name."";
}
else
{
$str.=$name";
}
$temp = $count+1;
$str = $this->sort_list($str,$rs[$i][id],$temp);
$i++;
}
return $str;
}

其中$this->sql对象为sql操作类对象,re_datas()函数返回查到的数组,sql_numrows()函数返回查询到的数目

调用方法:$sort_list = sort_list($sort_list,0,1);

实例上2


id 编号
fid 父分类编号
class_name 分类名
path 分类路径,以 id 为节点,组成类似 ,1,2,3,4, 这样的字符串
———————————————————————————-
可以假设有如下的数据
id fid class_name path
—————————————————-
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,
—————————————————-

 代码如下 复制代码
$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'].’
’;  
}  
?>  

代码

 代码如下 复制代码

$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'] . '
';
}
echo $option;
exit();
echo '';

热门栏目