<?php
$array =[
['id'=>1,'pid'=>0,'name'=>'电视'],
['id'=>2,'pid'=>1,'name'=>'美式电视'],
['id'=>3,'pid'=>1,'name'=>'中式电视'],
['id'=>4,'pid'=>2,'name'=>'美的'],
['id'=>5,'pid'=>2,'name'=>'中央'],
['id'=>6,'pid'=>0,'name'=>'冰箱'],
['id'=>7,'pid'=>6,'name'=>'制冷冰箱'],
['id'=>8,'pid'=>7,'name'=>'美的冰箱'],
];
 
/**
* 形成2叉树
*/
function getTree($array,$pid=0,$level=0,$html='-'){
$tree = array();
foreach($array as $row){
if($row['pid']==$pid){
$row['level']=$level+1;
$row['html']=str_repeat($html,$level);
$tree[]=$row;
$tree = array_merge($tree,getTree($array,$row['id'],$level+1,$html));
}
}
return $tree;
}
$result = getTree($array);
// print_r($result);
/**
* 显示二叉树
*/
function showTree($array){
$tab = "";
$tab.="<ul>";
foreach ($array as $row) {
$tab.="<li><a href=''>".$row['html'].$row['name']."</a></li>";
}
$tab.="</ul>";
echo $tab;
}
showTree($result);
 
/**
*
*/
function getParent($array,$id){
$parent=array();
foreach ($array as $row) {
if($row['id']==$id){
$parent[]=$row;
if($row['pid']>0){
$parent=array_merge($parent,getParent($array,$row['pid']));
}
}
}
return $parent;
}
$getParent = getParent($array,4);
for($i=count($getParent)-1;$i>=0;$i--){
// print_r($getParent[$i]);
if($i!=0) echo $getParent[$i]['name']."&gt;&gt;";
else echo $getParent[$i]['name'];
}
// print_r($getParent);
?>
posted on 2018-04-23 12:30  ksy_c  阅读(97)  评论(0)    收藏  举报