Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 关于递归调用的问题

关于递归调用的问题

Jun 23, 2016 pm 02:26 PM

我现在有一个数组,希望通过递归来实现分级
类似于树状,想要实现的效果如下:
标志(ID为1)
 |_307
    |_307两厢
    |_307三厢
 |_308
    |_308两厢
    |_308三厢
别克(ID为4)

定义的数组为
Array ( [1] => Array ( [1] => Array ( [2] => Array ( [0] => 307 ) [5] => Array ( [0] => 308 ) ) [2] => Array ( [3] => Array ( [0] => 307二厢 ) [7] => Array ( [0] => 307三厢 ) ) [5] => Array ( [6] => Array ( [0] => 308二厢 ) [8] => Array ( [0] => 308三厢 ) ) ) [4] => Array ( ) ).

其中别克现在为空数组,即[4] => array()
标志里的数组即  [1] => Array(  [1] => Array ( [2] => Ar .......
其中的匹配方法为;
[2] => Array ( [0] => 307 ) 的子级为 [2] => Array ( [3] => Array ( [0] => 307二厢 ) [7] => Array ( [0] => 307三厢 ) )

[5] => Array ( [0] => 308 ) 的子级为 [5] => Array ( [6] => Array ( [0] => 308二厢 ) [8] => Array ( [0] => 308三厢 ) )

我想问下,这样的结构能用递归来实现吗?如果是无限级的目录的话用这样的数组结构也可以实现吗?


回复讨论(解决方案)

<?php/*** 通用的树型类,可以生成任何树型结构 */header("content-type:text/html;charset=utf-8");class tree {	/**	* 生成树型结构所需要的2维数组	* @var array	*/	public $arr = array();	/**	* 生成树型结构所需修饰符号,可以换成图片	* @var array	*/	public $icon = array('│','├','└');	public $nbsp = " ";	/**	* @access private	*/	public $ret = '';	/**	* 构造函数,初始化类	* @param array 2维数组,例如:	* array(	*      1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),	*      3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),	*      4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),	*      5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三'),	*      6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),	*      7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二')	*      )	*/	public function __construct($arr=array()){       $this->arr = $arr;	   $this->ret = '';	   return is_array($arr);	}    /**	* 得到子级数组	* @param int	* @return array	*/	public function get_child($myid)	{		//$a = 			$newarr = array();		if(is_array($this->arr))		{			foreach($this->arr as $id => $a)			{							if($a['parentid'] == $myid) 				{									$newarr[$id] = $a;				}						}		}		return $newarr ? $newarr : false;	}      /**	* 得到树型结构	* @param int ID,表示获得这个ID下的所有子级	* @param string 生成树型结构的基本代码,例如:"<option value=\$id \$selected>\$spacer\$name</option>"	* @param int 被选中的ID,比如在做树型下拉框的时候需要用到	* @return string	*/	public function get_tree($myid, $str, $sid = 0, $adds = '', $str_group = '')	{		$number=1;		$child = $this->get_child($myid);		if(is_array($child))		{		    $total = count($child);			foreach($child as $id=>$value)			{				$j=$k='';				if($number==$total)				{					$j .= $this->icon[2]; //如果是最后一个子级使用└				}else				{					$j .= $this->icon[1];					$k = $adds ? $this->icon[0] : '';				}				$spacer = $adds ? $adds.$j : ''; //├								//$selected = $id==$sid ? 'selected' : ''; //下拉选择				@extract($value);//此方法为下面的字符变量赋上相应的键值 $nstr,$str_group				$parentid == 0 && $str_group ? eval("\$nstr = \"$str_group\";") : eval("\$nstr = \"$str\";");				$this->ret .= $nstr;				$nbsp = $this->nbsp;				$this->get_tree($id, $str, $sid, $adds.$k.$nbsp,$str_group); //如果子集是数组,递归调用 此处注意$adds参数				$number++;			}		}		return $this->ret;	}}$arr= array(	      1 => array('id'=>'1','parentid'=>0,'name'=>'世界'),	      3 => array('id'=>'3','parentid'=>1,'name'=>'中国'),	      4 => array('id'=>'4','parentid'=>1,'name'=>'美国'),	      5 => array('id'=>'5','parentid'=>3,'name'=>'湖南'),	      6 => array('id'=>'6','parentid'=>3,'name'=>'北京'),	      7 => array('id'=>'7','parentid'=>4,'name'=>'纽约'),	      7 => array('id'=>'7','parentid'=>5,'name'=>'长沙')	  );$tree = new tree($arr);$str = "<ul value=\$id >\$spacer\$name</ul>";echo $tree->get_tree(0,$str);?>
Copy after login

上面的树类是我在phpcms上扣下来整理的,可以放在apache目录下直接运行就可以看到效果,另外精华区有xuzuning版主各种树类。

多谢哈,参考了你给的这个代码,我改进了下自己的代码及数组结构,现在已经把该功能搞定了,多谢!给分

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles