当前位置:首页 > PHP教程 > php类库 > 列表

php树型类实例

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-02 21:09:08 浏览: 评论:0 

这篇文章主要介绍了php树型类,涉及数据结构与算法中的树结构,实例相对简单易懂,对于学习数据结构有一定的参考借鉴价值,需要的朋友可以参考下

本文实例讲述了php树型类。分享给大家供大家参考。具体分析如下:

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

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

希望本文所述对大家的PHP程序设计有所帮助。

Tags: php树型类

分享到: