标签:
<?php header("Content-Type:text/html;charset=utf-8"); $aarr = array( array(‘id‘=>1,‘name‘=>‘安徽‘,‘pid‘=>0), array(‘id‘=>2,‘name‘=>‘海淀‘,‘pid‘=>7), array(‘id‘=>3,‘name‘=>‘浣溪县‘,‘pid‘=>5), array(‘id‘=>4,‘name‘=>‘昌平‘,‘pid‘=>7), array(‘id‘=>5,‘name‘=>‘淮北‘,‘pid‘=>1), array(‘id‘=>6,‘name‘=>‘朝阳‘,‘pid‘=>7), array(‘id‘=>7,‘name‘=>‘北京‘,‘pid‘=>0), array(‘id‘=>8,‘name‘=>‘上地‘,‘pid‘=>2) ); //家谱树的应用,如面包屑导航,首页 > 手机类型 > GSM手机 > iPhone > iPhone6s function familytree($arr,$id){ $tree = array(); foreach($arr as $v){ if($v[‘id‘] == $id){ $tree[] = $v; if($v[‘pid‘] > 0){ array_push($tree,familytree($arr,$v[‘pid‘])); } } } return $tree; } echo "<pre>"; print_r(familytree($aarr,8));
这样好像是可以了,但实际上返回的是一个二维数组,所以还是不行,那么只能将使用array_push的用法换成array_merge了如下所示:
<?php header("Content-Type:text/html;charset=utf-8"); $aarr = array( array(‘id‘=>1,‘name‘=>‘安徽‘,‘pid‘=>0), array(‘id‘=>2,‘name‘=>‘海淀‘,‘pid‘=>7), array(‘id‘=>3,‘name‘=>‘浣溪县‘,‘pid‘=>5), array(‘id‘=>4,‘name‘=>‘昌平‘,‘pid‘=>7), array(‘id‘=>5,‘name‘=>‘淮北‘,‘pid‘=>1), array(‘id‘=>6,‘name‘=>‘朝阳‘,‘pid‘=>7), array(‘id‘=>7,‘name‘=>‘北京‘,‘pid‘=>0), array(‘id‘=>8,‘name‘=>‘上地‘,‘pid‘=>2) ); //家谱树的应用,如面包屑导航,首页 > 手机类型 > GSM手机 > iPhone > iPhone6s function familytree($arr,$id){ $tree = array(); foreach($arr as $v){ if($v[‘id‘] == $id){ $tree[] = $v; if($v[‘pid‘] > 0){ $tree = array_merge($tree,familytree($arr,$v[‘pid‘])); } } } return $tree; } echo "<pre>"; print_r(familytree($aarr,8));
标签:
原文地址:http://www.cnblogs.com/leigood/p/4907730.html