Home  >  Article  >  php教程  >  php+mysql无限级分类程序代码

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

WBOY
WBOYOriginal
2016-06-08 17:24:19994browse

无限级分类主要就是数据库中表的存储,一个是父ID,一个是子ID通过他们来查询父级关系,然后出来我们想要的

<script>ec(2);</script>

表结构: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 {
$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             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 '';

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn