PHP學習:Category類庫無限分類

學習是沒有盡頭的,只有在不斷的練習中才能提高自己。以下是本站小編精心爲大家整理的關於PHP語言學習的Category類庫 無限分類方面的知識,希望對大家有所幫助!更多內容請關注應屆畢業生網!

PHP學習:Category類庫無限分類

  以下是使用該類庫的方法

123include("Common/");$Category=newCategory("ArticleCategory",array('id','pid','name','fullname'));$categoryList=$Category->getList();

1、通過include包含類庫

2、通過new實例化類

3、調用getList()方法獲取所有分類列表

4、返回:所有分類列表,可以通過獲取fullname顯示參考。

  效果如圖:

  以下是類庫完整源碼:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216<?php/***類功能:php無限分類*author:*使用方法見:*/classCategory{private$model;//分類的數據表模型private$rawList=array();//原始的分類數據private$formatList=array();//格式化後的分類private$error="";//錯誤信息private$icon=array('&nbsp;&nbsp;│','&nbsp;&nbsp;├','&nbsp;&nbsp;└');//格式化的字符private$fields=array();//字段映射,分類id,上級分類pid,分類名稱name,格式化後分類名稱fullname/***構造函數,對象初始化*@paramarray,object$model數組或對象,基於TP3.0的.數據表模型名稱,若不採用TP,可傳遞空值。*@paramarray$field字段映射,分類cid,上級分類pid,分類名稱,格式化後分類名稱fullname*/publicfunction__construct($model='',$fields=array()){if(is_string($model)&&(!empty($model))){if(!$this->model=D($model))$this->error=$model."模型不存在!";}if(is_object($model))$this->model=&$model;$this->fields['cid']=$fields['0']?$fields['0']:'id';$this->fields['pid']=$fields['1']?$fields['1']:'pid';$this->fields['name']=$fields['2']?$fields['2']:'name';$this->fields['fullname']=$fields['3']?$fields['3']:'fullname';}/***獲取分類信息數據*@paramarray,string$condition查詢條件*@paramstring$orderby排序*/privatefunction_findAllCat($condition,$orderby=NULL){$this->rawList=$this->model->where($condition)->order($orderby)->select();}/***返回給定上級分類$pid的所有同一級子分類*@paramint$pid傳入要查詢的pid*@returnarray返回結構信息*/publicfunctiongetChild($pid){$childs=array();foreach($this->rawListas$Category){if($Category[$this->fields['pid']]==$pid){$childs[]=$Category;}}return$childs;}/***遞歸格式化分類前的字符*@paramint$cid分類cid*@paramstring$space*/privatefunction_searchList($cid=0,$space=""){$childs=$this->getChild($cid);//下級分類的數組//如果沒下級分類,結束遞歸if(!($n=count($childs))){return;}$m=1;//循環所有的下級分類for($i=0;$i<$n;$i++){$pre="";$pad="";if($n==$m){$pre=$this->icon[2];}else{$pre=$this->icon[1];$pad=$space?$this->icon[0]:"";}$childs[$i][$this->fields['fullname']]=($space?$space.$pre:"").$childs[$i][$this->fields['name']];$this->formatList[]=$childs[$i];$this->_searchList($childs[$i][$this->fields['cid']],$space.$pad."&nbsp;&nbsp;");//遞歸下一級分類$m++;}}
Copyright © 2024 筆墨谷 All Rights Reserved.