<?php
$arr=array(
array('id'=>'1','name'=>'吉林','parent'=>0),
array('id'=>'2','name'=>'北京','parent'=>0),
array('id'=>'3','name'=>'辽宁','parent'=>0),
array('id'=>'4','name'=>'吉林市','parent'=>1),
array('id'=>'5','name'=>'长春','parent'=>1),
array('id'=>'6','name'=>'海淀','parent'=>2),
array('id'=>'7','name'=>'大连','parent'=>3),
array('id'=>'8','name'=>'船营区','parent'=>4),
array('id'=>'9','name'=>'丰满区','parent'=>4)
);
//找子栏目
function findson($arr,$id=0){
$sons=array();
foreach($arr as $v){
if($v['parent']==$id){
$sons[]=$v;
}
}
return $sons;
}
//var_dump(findson($arr,$id=1));
//找子孙树
//用静态变量
function subtree($arr,$id,$lev=1){
static $subs=array(); //static 只初始化一次
foreach($arr as $v){
if($v['parent']==$id){
$v['lev']=$lev;
$subs[]=$v;
subtree($arr,$v['id'],$lev+1);
//不用静态变量
// $subs=array_merge($subs,subtree($arr,$v['id'],$lev+1));
}
}
return $subs;
}
/*
$tree=subtree($arr,$id=0,1);
foreach ($tree as $v){
echo str_repeat(' ',$v['lev']).$v['name']."<br/>";
}
*/
/**
家谱树应用
面包屑导航
首页>手机类型>诺基亚>
**/
function familytree($area,$id){
static $tree=array();
foreach($area as $v){
if($v['id']==$id){
$tree[]=$v;
//判断要不要继续找父栏目
if($v['parent']>0){
familytree($area,$v['parent']);
//不用static
//array_merge($area,familytree($area,$v['parent']));
}
}
}
return $tree;
}
echo "<hr>";
//print_r(familytree($arr,9));
/*用迭代找家谱树(推荐)*/
function familytree2($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(familytree2($arr,9));
?>