無限級分類主要就是數據庫中表的存儲,一個是父ID,一個是子ID通過他們來查詢父級關系,然后出來我們想要的.
表結構: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.="<span style='color:#CCCCCC'>".$name."</span>";
- }
- 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,
- —————————————————-
代碼如下:
- <?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>';
新聞熱點
疑難解答