您的位置:首页 > 其它

无极分类之子孙树、父辈树

2015-08-29 23:47 417 查看
无极分类之子孙树、父辈树

<?php
function subTree($arr, $id=0, $depth=0)
{
static $tree = array();
foreach ($arr as  $key=>$value) {
if($value['father_id'] == $id)
{
$value['depth'] = $depth;
$tree[] = $value;
subTree($arr, $value['id'], $depth+1);
//tree($arr, $value['id'],$depth+1);
}
}
return $tree;
}

function fatherTree($arr,$id) {
static $list = array();
foreach($arr as $v) {
if($v['id'] == $id) {
fatherTree($arr,$v['father_id']);
$list[] = $v;
}
}

return $list;
}

$arr = [
['id'=>1,'name'=>'news','father_id'=>0],
['id'=>2,'name'=>'article','father_id'=>0],
['id'=>3,'name'=>'local news','father_id'=>1],
['id'=>4,'name'=>'good article','father_id'=>2],
['id'=>5,'name'=>'bad article','father_id'=>2],
['id'=>6,'name'=>'sea','father_id'=>4],
];

$tree = subTree($arr);
foreach($tree as $v){
echo str_repeat('----',$v['depth']).$v['name'].$v['depth'].'<br>';
}

$list = fatherTree($arr,6);

foreach ($list as $key => $value) {
echo $value['name'].'>>';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: