The following editor will bring you a simple method to create an Infinitus classification tree structure. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
First, let’s take a look at the renderings
##The top category is actually a Second-level classification, second-level classification is also called a sub-category of first-level classification. On this basis, sub-categories can also have sub-categories, thus forming an infinite classification.Let’s look at the specific implementation code:
1. Query by field in the controller to query all classification information(id: the ID value of the category, cate_name: the name of the category, pid: parent ID, sorts: preparation for displaying the title order, optional.)
public function cate_display() { $cate = D('Cate'); $field = array('id','cate_name','pid','sorts'); $list = $cate->allCategory($field); $this->assign('list',$list); $this->display(); }
2. Code in the model
Create two methods in the model corresponding to the controller1. Query all classification information, and Call the method to generate a classification tree:
public function allCategory($field='*'){ $data = $this->field($field)->select(); return $this->tree($data); }
2. Generate a classification tree(use recursion, pass in data, and pid[parent class id ], level [number of layers, used to control the number of displays] two variables, the initial value is zero)
public function tree($data,$pid=0,$level=0){ static $tree = array(); foreach($data as $k=>$v){ if($v['pid'] == $pid){ $v['level'] = $level; $tree[]=$v; $this->tree($data,$v['id'],$level+1); } } return $tree; }
3. Code in the view file
The above is the detailed content of A brief introduction to the Infinitus classification tree structure. For more information, please follow other related articles on the PHP Chinese website!