首页 > 语言 > PHP > 正文

php树型菜单类

2024-09-04 11:44:04
字体:大 中 小
来源:转载
供稿:网友

原理简单,学过数据结构的一看就明白是什么道理了,不过今天在使用时数据中出现了子节点id(71)小于父节点id(104).导致部分子节点没被存储入数组,修改了一下,实例代码如下:

  1. <?php 
  2. class tree 
  3. { 
  4.     var $data = array(); 
  5.     var $child = array(-1=>array()); 
  6.     var $layer = array(-1=>-1); 
  7.     var $parent = array(); 
  8.     var $num = array(); 
  9.   
  10.     function setnode($id, $parent, $value,$num=0) 
  11.     { 
  12.         $parent = $parent ? $parent : 0; 
  13.   
  14.         $this->data[$id]  = $value; 
  15.         $this->num[$id]      = $num; 
  16.         if (!isset($this->child[$id])) $this->child[$id] = array(); 
  17.         $this->child[$parent][] = $id; 
  18.         $this->parent[$id]  = $parent; 
  19.   
  20.         if (!isset($this->layer[$parent]) && $parent == 0) 
  21.         { 
  22.            $this->layer[$id] = 0; 
  23.         } 
  24.         else 
  25.         { 
  26.             $this->layer[$id] = $this->layer[$parent] + 1; 
  27.         } 
  28.     } 
  29.   
  30.   
  31.     function getlist(&$tree, $root= 0) 
  32.     { 
  33.         foreach ($this->child[$root] as $key=>$id) 
  34.         { 
  35.             $tree[] = $id; 
  36.             if($this->child[$id]) $this->getlist($tree, $id); 
  37.         } 
  38.     } 
  39.   
  40.     function getvalue($id) 
  41.     { 
  42.   if($this->layer[$id]==0) 
  43.   { 
  44.    return $this->data[$id]; 
  45.   } 
  46.   else 
  47.   { 
  48.    return $leftmar.$this->data[$id]; 
  49.   } 
  50.     } 
  51.   
  52.     function getnum($id) 
  53.     { 
  54.   return $this->num[$id]; 
  55.     } 
  56.   
  57.     function getbitvalue($id) 
  58.     { 
  59.   return $this->data[$id]; 
  60.     } 
  61.   
  62.     function getlayer($id, $space = false) 
  63.     { 
  64.         return $space ? str_repeat($space, $this->layer[$id]) : $this->layer[$id]; 
  65.     } 
  66.   
  67.     function getparent($id) 
  68.     { 
  69.         return $this->parent[$id]; 
  70.     } 
  71.   
  72.     function getparents($id) 
  73.     { 
  74.         while ($this->parent[$id] != -1) 
  75.         { 
  76.             $id = $parent[$this->layer[$id]] = $this->parent[$id]; 
  77.         } 
  78.   
  79.         ksort($parent); 
  80.         reset($parent); 
  81.   
  82.         return $parent; 
  83.     } 
  84.   
  85.     function getchild($id) 
  86.     { 
  87.         return $this->child[$id]; 
  88.     } 
  89.   
  90.     function getchilds($id = 0) 
  91.     { 
  92.         $child = array($id); 
  93.         $this->getlist($child, $id); 
  94.   
  95.         return $child; 
  96.     } 
  97.   
  98.     function printdata() 
  99.     { 
  100.         return $this->layer; 
  101.     } 
  102. } 
  103. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表