刚刚写了个php无限递归...
时间:2010-08-11 来源:wyodyia
<?php
class Tree{
public $nodeId = array();
private $data = array();
public function __construct($result){
foreach ($result as $st){
$this->data[$st[0]]=$st[2];//保存ID对应的分类
$this->nodeId[$st[0]]=$st[1];//保存ID对应的父节点
}
}
//获取分类
public function getdate($id){
return $this->data[$id];
}
//遍利树
public function getNodeTree($id=0){
$childs=array();
foreach($this->nodeId as $child =>$pid){
if($pid == $id){
$childs[$child]=$this->getNodeTree($child);
}
}
return $childs;
}
//遍利节点
public function getChilds($id=0){
$childArray=array();
$childs=$this->getChild($id);
foreach($childs as $child){
$childArray[]=$child;
$childArray=array_merge($childArray,(array)$this->getChilds($child));
}
return $childArray;
}
public function getChild($id){
$childs = array();
foreach($this->nodeId as $child => $pid){
if($pid == $id){
$childs[$child]=$child;
}
}
return $childs;
}
//遍利深度
public function level($id = 0){
$chlids = array();
foreach ($this->nodeId as $child => $pid){
if ($id == $child){
$chlids[$child]=$child;
$chlids = array_merge($chlids,(array)$this->level($pid));
}
}
return $chlids;
}
public function getLevel($cnt){
return str_repeat("|-",count($this->level($cnt)));
}
}
$result = array(
array(1, 0, '目录1', 0),array(2, 1, '目录2', 0),array(5, 3, '目录5', 1),array(3, 0, '目录3', 3),array(4, 2, '目录4', 4),
array(9, 4, '目录9', 4),array(6, 2, '目录6', 5),array(7, 2, '目录7', 5),array(8, 3, '目录8', 5),array(10, 8, '目录10', 5)
);
$Tree = new Tree($result);
$sortDate = $Tree->getChilds();
foreach($sortDate as $v => $p){
echo $Tree->getLevel($p).$Tree->getDate($p)."<br>";
}
echo "<br>获取同级子类--------------------------------------------------------><br>";
print_r($Tree->getChild(0));
echo "<Br><Br>从某个节点开始便利.默认从跟节点--------------------------------------------------------><br>";
print_r($Tree->getChilds());
echo "<Br><Br>获取节点的深度--------------------------------------------------------><br>";
echo "深度";
print_r(count($Tree->level(9)));
echo "--> ";
print_r($Tree->level(9));
?>