php树型菜单类

原理简单,学过数据结构的一看就明白是什么道理了,不过今天在使用时数据中出现了子节点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. function setnode($id, $parent, $value,$num=0)
  10. {
  11. $parent = $parent ? $parent : 0;
  12. $this->data[$id] = $value;
  13. $this->num[$id] = $num;
  14. if (!isset($this->child[$id])) $this->child[$id] = array();
  15. $this->child[$parent][] = $id;
  16. $this->parent[$id] = $parent;
  17. if (!isset($this->layer[$parent]) && $parent == 0)
  18. {
  19. $this->layer[$id] = 0;
  20. }
  21. else
  22. {
  23. $this->layer[$id] = $this->layer[$parent] + 1;
  24. }
  25. }
  26. function getlist(&$tree, $root= 0)
  27. {
  28. foreach ($this->child[$root] as $key=>$id)
  29. {
  30. $tree[] = $id;
  31. if($this->child[$id]) $this->getlist($tree, $id);
  32. }
  33. }
  34. function getvalue($id)
  35. {
  36. if($this->layer[$id]==0)
  37. {
  38. return $this->data[$id];
  39. }
  40. else
  41. {
  42. return $leftmar.$this->data[$id];
  43. }
  44. }
  45. function getnum($id)
  46. {
  47. return $this->num[$id];
  48. }
  49. function getbitvalue($id)
  50. {
  51. return $this->data[$id];
  52. }
  53. function getlayer($id, $space = false)
  54. {
  55. return $space ? str_repeat($space, $this->layer[$id]) : $this->layer[$id];
  56. }
  57. function getparent($id)
  58. {
  59. return $this->parent[$id];
  60. }
  61. function getparents($id)
  62. {
  63. while ($this->parent[$id] != -1)
  64. {
  65. $id = $parent[$this->layer[$id]] = $this->parent[$id];
  66. }
  67. ksort($parent);
  68. reset($parent);
  69. return $parent;
  70. }
  71. function getchild($id)
  72. {
  73. return $this->child[$id];
  74. }
  75. function getchilds($id = 0)
  76. {
  77. $child = array($id);
  78. $this->getlist($child, $id);
  79. return $child;
  80. }
  81. function printdata()
  82. {
  83. return $this->layer;
  84. }
  85. }
  86. ?>