刚刚写了个PHP无限递归

<?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));
?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值