基于递归实现的php树形菜单代码_php技巧
本文实例讲述了基于递归实现的php树形菜单代码。分享给大家供大家参考。具体实现方法如下:
开发电子商务网站的时候,做了这个显示树形菜单的功能,用的递归实现的PHP树形菜单函数。具体代码如下:
$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程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

In this chapter, we are going to learn the following topics related to routing ?

Validator can be created by adding the following two lines in the controller.
