Attention to infinite classification

Keywords: PHP Database

Infinite level classification is mainly realized by recursive algorithm and special data table design

My code

 1 /**
 2      * Get the menu information of the order
 3      * Using recursive methods
 4      */
 5     public function getHierarchicalMenus($pid , $condition=array() , $cid = 0){
 6         $data = array();
 7         if (!isset($condition['status'])){
 8             $condition['status'] = array('neq' , -1);
 9         }
10         $condition['parentid'] = $pid;
11         $menus = $this->_db->where($condition)->order("listorder desc")->select();
12         if ($menus){
13             foreach ($menus as $v){
14                 $res = $this->getHierarchicalMenus($v['menu_id'] ,$condition ,$cid+1);
15                 if ($res){
16                     $v['child'] = $res;
17                     $v['cid'] = $cid;
18                 }else{
19                     $v['child'] = 0;
20                 }
21                 $v['cid'] = $cid;
22                 $data[] = $v;
23             }
24         }
25         return $data;
26     }

Teacher's code

 1 public function getTree()
 2     {
 3         $data = $this->select();
 4         return $this->_reSort($data);
 5     }
 6     private function _reSort($data, $parent_id=0, $level=0, $isClear=TRUE)
 7     {
 8         static $ret = array();
 9         if($isClear)
10             $ret = array();
11         foreach ($data as $k => $v)
12         {
13             if($v['parent_id'] == $parent_id)
14             {
15                 $v['level'] = $level;
16                 $ret[] = $v;
17                 $this->_reSort($data, $v['id'], $level+1, FALSE);
18             }
19         }
20         return $ret;
21     }

Obviously, the infinite level I designed is nested with array, so there is a big problem in the foreground display,

Nesting several layers of corresponding display requires several layers of judgment plus loop. However, the teacher uses two-dimensional array through level

To determine the level, the order is constant due to continuous depth, and all data is recorded before recursion, reducing

The number of database operations, improve the database concurrent operations.

Posted by gray_bale on Sat, 02 May 2020 22:01:29 -0700