欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

如何提高php无限分类查询的效率(使用数组和递归)

程序员文章站 2024-04-05 16:59:48
...
如何提高php无限分类查询的效率(使用数组递归)
<?php
class Tree {
    /**
     * 从数据库查询出的所有分类信息
     * @var array
     * by:bbs.it-home.org
     */
    var $arr;
    /**
     * 如下格式
     * var $arr = array(
     1 => array(‘id’=>’1′,’parentid’=>0,’name’=>’一级栏目一’),
     2 => array(‘id’=>’2′,’parentid’=>0,’name’=>’一级栏目二’),
     3 => array(‘id’=>’3′,’parentid’=>1,’name’=>’二级栏目一’),
     );*/
    /**
     * 输出结构
     * @var array
     */
    var $tree = array();
    /**
     * 树形递归的深度
     * @var int
     */
    var $deep = 1;
    /**
     * 生成树形的修饰符号
     * @var array
     */
    var $icon = array('│','├','└');
    /**
     * 生成指定id的下级树形结构
     * @param int $rootid 要获取树形结构的id
     * @param string $add 递归中使用的前缀
     * @param bool $parent_end 标识上级分类是否是最后一个
     */
    function getTree($rootid = 0,$add = "",$parent_end =true){
        $is_top = 1;
        $child_arr = $this->getChild($rootid);
        if(is_array($child_arr)){
            $cnt = count($child_arr);
            foreach($child_arr as $key => $child){
                $cid = $child['id'];
                $child_child = $this->getChild($cid);
                if($this->deep >1){
                    if($is_top == 1 && $this->deep > 1){
                        $space = $this->icon[1];
                        if(!$parent_end)
                        $add .= $this->icon[0];
                        else $add .= "";
                    }
                    if($is_top == $cnt){
                        $space = $this->icon[2];
                        $parent_end = true;
                    }else {
                        $space = $this->icon[1];
                        $parent_end = false;
                    }
                }
                $this->tree[] = array(‘spacer’=>$add.$k.$space,
                ‘name’=>$child['name'],
                ‘id’=>$cid
                );
                $is_top++;
                $this->deep++;
                if($this->getChild($cid))
                $this->getTree($cid,$add,$parent_end);
                $this->deep–;
            }
        }
        return $this->tree;
    }
    /**
     * 获取下级分类数组
     * @param int $root
     */
    function getChild($root = 0){
        $a = $child = array();
        foreach($this->arr as $id=>$a){
            if($a['parentid'] == $root){
                $child[$a['id']] = $a;
            }
        }
        return $child?$child:false;
    }
    /**
     * 设置源数组
     * @param $arr
     */
    function setArr($arr = array()){
        $this->arr = $arr;
    }
}
?>

通过一次查询把结构保存进一个数组,再数组进行递归运算,无疑极大的提高了程序运行效率。 代码的使用很简单:得到查询结构后setArr,直接调用getTree, 皆可以得到按照程序排序号并带有前缀修饰等信息的数组。通过foreach这个数组可以得到如下的树状列表: 水果 ├香蕉 ├苹果 │├红富士 │└海南苹果 └桃子 记住:网站开发过程中,多数的瓶颈在数据库,而非php代码

以上就是如何提高php无限分类查询的效率(使用数组和递归)的内容,更多相关内容请关注PHP中文网(www.php.cn)!