无限级分类注意

无限级分类主要救赎采用递归算法和特殊的数据表设计实现的

我的代码

 1 /**
 2      * 获取顺序的菜单信息
 3      * 使用递归方法
 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     }

老师的代码

 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     }

明显不同,我设计的无限级是使用array进行嵌套,那么前台的显示就有很大的问题了,

嵌套几层相应的显示就要几层判断加循环,然而老师的使用的是二维array,通过level

来判断层级,顺序由于持续深入不变,同时在递归之前先将全部数据先记录下来,减少

数据库操作次数,提高数据库并发操作。

posted @ 2018-01-25 16:19  xueheo  阅读(278)  评论(0编辑  收藏  举报