递归实现无限级分类查找子孙树

$arr = array(   
	0=>array('id'=>1,'pid'=>0,'name'=>'亚洲'),
	1=>array('id'=>2,'pid'=>0,'name'=>'北美洲'),  
	2=>array('id'=>3,'pid'=>1,'name'=>'中国'),  
	3=>array('id'=>4,'pid'=>2,'name'=>'美国'),  
	4=>array('id'=>5,'pid'=>3,'name'=>'北京'),
	5=>array('id'=>6,'pid'=>3,'name'=>'上海'),
	6=>array('id'=>7,'pid'=>5,'name'=>'海淀区'),
);

function getSons($arr,$id=0)
{
	//定义一个临时的空数组存放排序后的数据
	$temp=array();
	//遍历整个数组,查找符合条件的子孙
	foreach($arr as $v)
	{
		//如果数组中某个元素的父id等于传参过来的id,说明这个元素是它的子孙
		if($v['pid']==$id)
		{
			//将此元素存入临时的数组中
			$temp[]=$v;
			//利用递归的方法,再次调用自身,查找这个元素本身还有没有子孙
			$temp=array_merge($temp,getSons($arr,$v['id']));
			
		}
	}	
	return $temp;
}

var_dump( getSons($arr,0));

代码解析:
第一次循环的时候,肯定是亚洲符合条件,所以亚洲会被存入临时数组。注意这时第一层循环并不会继续执行下去,因为我们这个时候要去查找亚洲还有没有子孙。通过调用自身,再次进入第二层循环,这次我们找到了中国,找到中国后,第二层又会被打断,进入第三层,找到了北京,第三层被打断,进入第四层,找到了海淀,第四层被打断,进入第五层,找海淀的子孙,通过遍历数组可知,海淀并没有子孙。第五层会继续执行下去,就是最后一句return t e m p 。 这 个 函 数 的 返 回 值 会 返 回 到 第 四 层 中 调 用 他 的 地 方 , 当 然 这 里 的 temp。这个函数的返回值会返回到第四层中调用他的地方,当然这里的 temptemp是个空数组。第四层会继续执行下去, t e m p 里 此 时 包 含 海 淀 , 返 回 到 第 三 层 , temp里此时包含海淀,返回到第三层, temptemp里包含了北京和海淀,以此类推,第二层中国,北京,海淀,第一层亚洲,中国,北京,海淀。到此时第一层循环继续执行下去,会找到和亚洲平级的北美洲,北美洲又会通过递归查找自己的子孙,一层一层嵌套执行下去。

注意:每次函数递归调用的时候,$temp都会被初始化,这样保存的数据就会丢失,所以要用array_merge函数把两个数组的数据整合在一起。

递归图解:
递归调用图示

无限(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值