Home  >  Article  >  php教程  >  基于递归实现的php树形菜单代码

基于递归实现的php树形菜单代码

WBOY
WBOYOriginal
2016-06-06 20:17:121544browse

这篇文章主要介绍了基于递归实现的php树形菜单代码,采用了递归的方法遍历节点构造出树形菜单,是非常实用的技巧,需要的朋友可以参考下

本文实例讲述了基于递归实现的php树形菜单代码。分享给大家供大家参考。具体实现方法如下:

开发电子商务网站的时候,做了这个显示树形菜单的功能,用的递归实现的PHP树形菜单函数。具体代码如下:

复制代码 代码如下:

public function procCategory($sid,$pid){
$return = array();
$key = 0;
static $arr = array(); //分类级别参考数组
$sql =  "select cid,pcid,name from shop_goods_catalog where sid='{$sid}' and pcid = '{$pid}'";
$result = $this->__db->query($sql);
 
while($row=$this->__db->fetchArray($result)){
$nbsp = '';
if($row['pcid']==0){
$arr = array();
}
$arr[] = $row['pcid'];
//顶级分类不添加树形结构标识。
if($row['pcid']>0){
//根据分类级别添加树形结构标识
$key = array_search($row['pcid'],$arr);
for($i=0;$i $nbsp .= '  ';
}
//重构分类级别参考数组
if(count($arr)>1&&count(array_keys($arr,$row['pcid']))>1){
$arr = array_slice($arr,0,$key+1);
}
}
$row['name'] = $nbsp.$row['name'];
$row['level'] = $key; //分类级别,0为顶级分类,1为二级分类,用于样式设定或其他需求
$return[] = $row;
$r = $this->procCategory($sid,$row['cid']);
$return = array_merge($return,$r);
}
 
return $return;
}


由于递归的效率相对较低,如果注重程序效率的话,,不要用此方法,或者对此方法进行改进使用。

希望本文所述对大家的PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn