Home > php教程 > PHP源码 > PHP 递归

PHP 递归

PHP中文网
Release: 2016-05-26 08:18:15
Original
1012 people have browsed it

php代码

<?php
class TestControl extends Control{
	private $temp = array(
			array("id"=>3,"name"=>"小说","pid"=>1),
			array("id"=>4,"name"=>"足球","pid"=>2),
			array("id"=>1,"name"=>"书","pid"=>0),
			array("id"=>2,"name"=>"球","pid"=>0),
			array("id"=>5,"name"=>"陶瓷","pid"=>0),
			array("id"=>6,"name"=>"言情小说","pid"=>3)
	);
	public function __construct(){
		parent::__construct();
	}
	
	public function recursion(){
		$ret = $this->recursionArray($this->temp,0);
		$html = $this->cHtml($ret);
		echo $html;
	}
	
	public function recursionArray($arr,$pid){
		$tree = &#39;&#39;;
		foreach ($arr as $key=>$value){
			if($value[&#39;pid&#39;] == $pid){
				$value[&#39;pid&#39;] = $this->recursionArray($arr,$value[&#39;id&#39;]);
				$tree[] = $value;
			}
		}
		return $tree;
	}
	
	public function cHtml($arr){
// 		$html = "";
// 		foreach ($arr as $key=>$value){
// 			if($value[&#39;pid&#39;] == $pid){
// 				$html .= "<ul>";
// 				$html .= "<li class=&#39;&#39;>".$value[&#39;name&#39;];
// 				$html .= $this->cHtml($arr,$value[&#39;id&#39;]);
// 				$html .= "</li>";
// 				$html .= "</ul>";
// 			}
// 		}
// 		return $html;
		$html = "";
		$html .= "<ul>";
		foreach ($arr as $key=>$value){
			
			if(is_array($value[&#39;pid&#39;])){
				$html .="<li class=&#39;main&#39;>".$value[&#39;name&#39;];
				$html .= $this->cHtml($value[&#39;pid&#39;]);
			}else {
				$html .="<li class=&#39;&#39;>".$value[&#39;name&#39;];
			}
			
			$html .= "</li>";
		}
		$html .= "</ul>";
		return $html;
	}
}
Copy after login
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template