欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP 递归

程序员文章站 2022-06-06 20:04:00
...
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 = '';
		foreach ($arr as $key=>$value){
			if($value['pid'] == $pid){
				$value['pid'] = $this->recursionArray($arr,$value['id']);
				$tree[] = $value;
			}
		}
		return $tree;
	}
	
	public function cHtml($arr){
// 		$html = "";
// 		foreach ($arr as $key=>$value){
// 			if($value['pid'] == $pid){
// 				$html .= "<ul>";
// 				$html .= "<li class=''>".$value['name'];
// 				$html .= $this->cHtml($arr,$value['id']);
// 				$html .= "</li>";
// 				$html .= "</ul>";
// 			}
// 		}
// 		return $html;
		$html = "";
		$html .= "<ul>";
		foreach ($arr as $key=>$value){
			
			if(is_array($value['pid'])){
				$html .="<li class='main'>".$value['name'];
				$html .= $this->cHtml($value['pid']);
			}else {
				$html .="<li class=''>".$value['name'];
			}
			
			$html .= "</li>";
		}
		$html .= "</ul>";
		return $html;
	}
}
相关标签: PHP 递归