);
/**
*1.递归,查找子孙树
*/
function subtree($arr, $id=0, $lev=1) {
// 子孙数组
$subs = array();
foreach($arr as $v) {
// 取父类
if($v['parent'] == $id) {
$v['lev'] = $lev;
// 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0)
$subs[] = $v;
$subs = array_merge($subs, subtree($arr, $v['id'], $lev+1));
}
}
return $subs;
}
$tree = subtree($area, 0, 1);
foreach($tree as $v) {
echo str_repeat(' ', $v['lev']), $v['name'],'
';
}
/**
*2.递归,求家谱树
*/
function familytree($arr,$id) {
$tree = array();
foreach($arr as $v) {
// 判断要不要找父栏目
if($v['id'] == $id) {
// parnet>0,说明有父栏目
if($v['parent'] > 0) {
$tree = array_merge($tree,familytree($arr,$v['parent']));
}
// 以找到上地为例
$tree[] = $v;
}
}
return $tree;
}
// 北京->海淀->上地
print_r(familytree($area,8));
/**
* 2.迭代,求家谱树
*迭代,效率比递归高,代码也没多.
*找家谱树推荐用迭代
*/
function tree($arr,$id) {
$tree = array();
while($id !== 0) {
foreach($arr as $v) {
if($v['id'] == $id) {
$tree[] = $v;
$id = $v['parent'];
break;
}
}
}
return $tree;
}
print_r(tree($area,8));