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

原创
2016-06-07 11:40:25806浏览
如何提高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代码。
以上案例转载地址:http://www.jb100.net/html/content-22-641-1.html

希望这个案例能帮到大家,有需要的朋友可以参考一下。

AD:真正免费,域名+虚机+企业邮箱=0元

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。