解析thinkphp的左右值无限分类


Posted in PHP onJune 20, 2013

以前一直使用父子无限分类,这种分类结构清晰,使用也简单。但若分类数量很大的话,在查询上性能不佳。比如在做导航菜单中,我要根据某一分类查询出整个分类树的话(祖辈)。
性能消耗是非常大的,要么做递归,要么做多次查询。故,对于分类的数据量很大的情况,我推荐使用左右值,以减少查询上的麻烦。

_id
    /**
         +----------------------------------------------------------
         * 构造函数
         * @access public
         * @return void
         +----------------------------------------------------------
         */
    public  function __construct($left,$right,$id){
        parent::__construct();
       $this->_left = $left;
       $this->_right = $right;
       $this->_id = $id;
    }
    /**
      +----------------------------------------------------------
      * 根据node$this->_id得到该node的所有值
      * @access public
      * @param $nodeId
      * @return array
      +----------------------------------------------------------
     */     
    public  function getNodeById($nodeId)
    {
        if($nodeId>0)
        {
            return $this->getById($nodeId);
        }
        else
        {
            throw_exception('未知$this->_id');
            return false;
        }
    }
    /**
           +----------------------------------------------------------
           * 获取父节点,含直属父类(type=1),所有父类:type=0
           * @access public 
           * @param $nodeId int 节点$this->_id
           * @return $parentNode array()
           +----------------------------------------------------------
          */     
    public  function getParentNode($nodeId,$type = 0)
    {
        if($nodeId == 0) throw_exception('未知$this->_id');;
        $currentNode = $this->getNodeById($nodeId);
        if($currentNode)
        {
            $condition = " ".$this->_left.'<'.$currentNode[$this->_left].' and '.$this->_right.' >'.$currentNode[$this->_right]." ";
            if($type ==1) //直属父类
            {
                return $this->where($condition)->order($this->_left." DESC")->limit(1)->find();
                //                $sql = "SELECT * FROM ".TABLE_NAME." WHERE {$condition} ORDER BY ".$this->_left." DESC LIMIT 1";
                //                return mysql_query($sql) or die(mysql_error());
            }
            else if($type ==0)
            {
                return $this->where($condition)->findAll();
                //                $sql = "SELECT * FROM ".TABLE_NAME." WHERE {$condition} ";
                //                return mysql_query($sql) or die(mysql_error());
            }
        }
        else
        {
            return false;
        }
    }
    /**
         +----------------------------------------------------------
         * 当前节点下子孙节点总数.子孙总数=(当前节点的右值 - 当前节点的左值-1)/2
         * @access public 
         * @param $node_id int 节点$this->_id
         * @return $amount int 该节点下的子孙总数         * 
         +----------------------------------------------------------
         */
    public  function getChildCount($nodeId)
    {
        $currentNode = $this->getNodeById($nodeId);
        if(!empty($currentNode))
        {
            return (int)($currentNode[$this->_right]-$currentNode[$this->_left] -1)/2;
        }
    }
    /**
      +----------------------------------------------------------
      * 获取当前节点下所有子节点。 当 A子类的右节点=B子类左节点-1 则 A、B属于同一级别
      * @access public 
      * @param $curentId
      * @param  $type int 0:当前节点下所有子类,1为当前节点下一级子类
      * @return bool
      +----------------------------------------------------------
     */     
    public  function getChild($nodeId,$type=0)
    {
        $currentNode = $this->getNodeById($nodeId);
        if($currentNode[$this->_left]-$currentNode[$this->_right] ==1)
        {
            return false; //当 该节点左值 - 右值=1  时,其下没有子节点。
        }
        else
        {
            $condition = $this->_left.'>'.$currentNode[$this->_left].' and '.$this->_right .'<'.$currentNode[$this->_right];
            $child = $this->where($condition)->findAll();
            if($type == 0)//所有子类
            {
                return $child;
            }
            else if($type ==1) //获取当前节点下一级分类
            {                        
                $subArr = array(); //一级子类
                foreach ($child as $k=>$sub) {
                    //子类的左节点=父类左节点+1,则子类为第一个子类
                    if($sub[$this->_left]==$currentNode[$this->_left]+1)
                    {
                        //$right = $sub[$k][$this->_right]; //当前节点的右节点
                        $firstSub = $sub; //当前节点下第一个子类
                        array_push($subArr,$firstSub); //子类入栈
                        unset($child[$k]);
                    }
                }
                $rightVal =  $firstSub[$this->_right]; //第一个子节点为比较标志
                $childCount = count($child);//剩余子节点数
                for($i=0;$i<$childCount;$i++) //循环检索出 同级子节点
                {
                    foreach ($child as $key => $sub2) {
                        if($rightVal == $sub2[$this->_left]-1)
                        {
                            $rightVal = $sub2[$this->_right]; //把循环当前的node的右节点当做比较值
                            array_push($subArr,$sub2);
                            unset($child[$key]);
                        }
                    }
                }
                return $subArr;
            }
        }
    }
    /**
         +----------------------------------------------------------
         * 返回当前节点的完整路径
         * @access public 
         * @param $nodeId
         * @return array
         +----------------------------------------------------------
        */     
    public  function getSinglePath($nodeId)
    {
        $sql = "select parent.* from __TABLE__ as node,__TABLE__ as parent where node.{$this->_left} between parent.{$this->_left}
            AND parent.{$this->_right} AND node.{$this->_id} = {$nodeId} order by parent.{$this->_left}";
//        echo $sql;
        return $this->query($sql);
    }
    /**
      +----------------------------------------------------------
      * 添加子节点,分3种:0:在当前节点下最后追加一个子节点;1:在当前节点下追加第一个子节点;

2:在当前节点下的某个子节点后追加
      * @access public 
      * @param $currentId int 
      * @param $nodeName string 新节点名称      
      * @param $targetId int 追加到当前节点下子节点的指定节点后
      * @return bool
      +----------------------------------------------------------
     */    
    public  function addNode($nodeId,$newData,$type=0,$targetId=0)
    {
        if(empty($newData))
        {
            throw_exception('新分类不能为空');
        }
        $currentNode = $this->getNodeById($nodeId);
        switch ($type) {
            case 0:
                $leftNode  = $currentNode[$this->_right]; //新节点的左值为父节点的右值
                $rightNode = $leftNode+1;
                break;
            case 1:
                $leftNode = $currentNode[$this->_left]+1; //新节点的左值为父节点的左值+1
                $rightNode = $leftNode+1;
                break;
            case 2:
                $otherNode = $this->getNodeById($targetId);
                $leftNode = $otherNode[$this->_right]+1;
                $rightNode = $leftNode+1;
            default:
                break;
        }
//         $sql = "UPDATE ".TABLE_NAME." SET ".$this->_right."=".$this->_right."+2 WHERE ".$this->_right." >= ".$leftNode;
//        $sql2 = "UPDATE ".TABLE_NAME." SET ".$this->_left."=".$this->_left."+2 WHERE ".$this->_left.">".$leftNode;
        $this->setInc($this->_right,$this->_right.">=".$leftNode,2); //把所有右值大于新节点左值的节点的右值+2,注意效率
        $this->setInc($this->_left,$this->_left.">".$leftNode,2);   //把所有大于新节点的左值+2
        $newData[$this->_left] = (int)$leftNode;
        $newData[$this->_right] =(int) $rightNode;
        return $this->add($newData);
    }
    /**
         +----------------------------------------------------------
         * 删除节点
         * @access public 
         * @param type 操作类型,默认为0删除当前节点下的所有子节点,1为删除包括自身的节点
         * @param $nodeId int 要删除的$this->_id
         * @return bool
         +----------------------------------------------------------
        */     
    public  function rmNode($nodeId,$type =1)
    {
        $currentNode = $this->getNodeById($nodeId);
        if($type == 1) //删除包含自身的节点
        {
            $sql = "DELETE FROM __TABLE__ WHERE ".$this->_left.">= {$currentNode[$this->_left]} AND ".$this->_right."<= {$currentNode[$this->_right]}";
            $childCount = ($this->getChildCount($nodeId)+1)*2; //要更新的值
            $sql2 = "UPDATE  __TABLE__  SET ".$this->_right."=".$this->_right."-".$childCount." WHERE ".$this->_right.">".$currentNode[$this->_right];
            $sql3 = "UPDATE  __TABLE__  SET ".$this->_left."=".$this->_left."-".$childCount." WHERE ".$this->_left.">".$currentNode[$this->_left];
        }
        else //删除当前节点下的所有节点
        {
            $sql ="DELETE FROM __TABLE__ WHERE ".$this->_left."> {$currentNode[$this->_left]} AND ".$this->_right."< {$currentNode[$this->_right]}";
            $childCount = $this->getChildCount($nodeId)*2; //要更新的值
            $sql2 = "UPDATE __TABLE__ SET ".$this->_right."=".$this->_right ."-".$childCount." WHERE ".$this->_right.">=".$currentNode[$this->_right];
            $sql3 = "UPDATE __TABLE__ SET ".$this->_left."=".$this->_left."-".$childCount." WHERE ".$this->_left.">".$currentNode[$this->_left];
        }
         $this->execute($sql);  
         $this->execute($sql2);  
         $this->execute($sql3);  
        return true;
    }
     /**
      +----------------------------------------------------------
      * 修改节点,名称等
      * @access public 
      * @param $newData array()必须含有 要修改的$this->_id,k-v必须对齐,如arr['node_name'] = '商品'
      * @return bool
      +----------------------------------------------------------
     */     
    public  function modiNode($newData)
       {
            if(!empty($newData))
            {
                $id = $newData[$this->_id];                
                unset($newData[$this->_id]);
                return $this->save($newData,$this->_id.'='.$id);                               
          }
       }
}
?>

PHP 相关文章推荐
PHP安全编程之加密功能
Oct 09 PHP
做个自己站内搜索引擎
Oct 09 PHP
通过ICQ网关发送手机短信的PHP源程序
Oct 09 PHP
PHP 远程关机实现代码
Nov 10 PHP
php数据库抽象层 PDO
May 07 PHP
超级实用的7个PHP代码片段分享
Jan 05 PHP
php小经验:解析preg_match与preg_match_all 函数
Jun 29 PHP
zend framework框架中url大小写问题解决方法
Aug 19 PHP
简单谈谈php中的unicode和utf8编码
Jun 10 PHP
php实现QQ空间获取当前用户的用户名并生成图片
Jul 25 PHP
php 处理png图片白色背景色改为透明色的实例代码
Dec 10 PHP
PHP实现的杨辉三角求解算法分析
Mar 11 PHP
PHP 清空varnish 缓存的详解(包括指定站点下的)
Jun 20 #PHP
PHP array_multisort() 函数的深入解析
Jun 20 #PHP
PHP操作MongoDB GridFS 存储文件的详解
Jun 20 #PHP
解析Linux下Varnish缓存的配置优化
Jun 20 #PHP
解析PHP中常见的mongodb查询操作
Jun 20 #PHP
PHP 解决session死锁的方法
Jun 20 #PHP
解析PHP可变函数的经典用法
Jun 20 #PHP
You might like
php源码 fsockopen获取网页内容实例详解
2016/09/24 PHP
PHP数组的定义、初始化和数组元素的显示实现代码
2016/11/05 PHP
thinkPHP简单导入和使用阿里云OSSsdk的方法
2017/03/15 PHP
php使用PDO下exec()函数查询执行后受影响行数的方法
2017/03/28 PHP
PHP将身份证正反面两张照片合成一张图片的代码
2017/04/08 PHP
PHP获取文本框、密码域、按钮的值实例代码
2017/04/19 PHP
PHP7新特性
2021/03/09 PHP
jQuery中filter(),not(),split()使用方法
2010/07/06 Javascript
Extjs显示从数据库取出时间转换JSON后的出现问题
2012/11/20 Javascript
Jquery 跨域访问 Lightswitch OData Service的方法
2013/09/11 Javascript
文本框只能选择数据到文本框禁止手动输入
2013/11/22 Javascript
javascript遇到html5的一些表单属性
2015/07/05 Javascript
js绘制圆形和矩形的方法
2015/08/05 Javascript
jquery实现左右轮播图效果
2017/09/28 jQuery
浅谈Vue页面级缓存解决方案feb-alive(上)
2019/04/14 Javascript
JS使用百度地图API自动获取地址和经纬度操作示例
2019/04/16 Javascript
vue+element加入签名效果(移动端可用)
2019/06/17 Javascript
解决layui的使用以及针对select、radio等表单组件不显示的问题
2019/09/05 Javascript
Vue数据双向绑定底层实现原理
2019/11/22 Javascript
React Ant Design树形表格的复杂增删改操作
2020/11/02 Javascript
[40:06]DOTA2亚洲邀请赛 4.3 突围赛 Liquid vs VGJ.T 第一场
2018/04/04 DOTA
详解Python中for循环的使用
2015/04/14 Python
python中set常用操作汇总
2016/06/30 Python
python中利用zfill方法自动给数字前面补0
2018/04/10 Python
python调用API实现智能回复机器人
2018/04/10 Python
PyTorch读取Cifar数据集并显示图片的实例讲解
2018/07/27 Python
基于django channel实现websocket的聊天室的方法示例
2019/04/11 Python
python实现微信自动回复机器人功能
2019/07/11 Python
jupyter notebook 多行输出实例
2020/04/09 Python
解析python 类方法、对象方法、静态方法
2020/08/15 Python
Python如何执行系统命令
2020/09/23 Python
华纳兄弟工作室的官方授权商店:WB Shop
2018/11/30 全球购物
优秀中职教师事迹材料
2014/08/26 职场文书
2014年教育培训工作总结
2014/12/08 职场文书
主持人大赛开场白
2015/05/29 职场文书
创业计划书之服装
2019/10/07 职场文书