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

WBOY
Release: 2016-05-31 19:27:34
Original
994 people have browsed it

本文实例讲述了基于递归实现的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程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!