1. /**
2. * author: askie
3. * blog: http://www.pkphp.com
4. * 版权: 随便用
5. * 无限分类
6. */
7. class Tree
8. {
9. public $data=array();
10. public $cateArray=array();
11.
12. function Tree()
13. {
14.
15. }
16. function setNode ($id, $parent, $value)
17. {
18. $parent = $parent?$parent:0;
19. $this->data[$id] = $value;
20. $this->cateArray[$id] = $parent;
21. }
22. function getChildsTree($id=0)
23. {
24. $childs=array();
25. foreach ($this->cateArray as $child=>$parent)
26. {
27. if ($parent==$id)
28. {
29. $childs[$child]=$this->getChildsTree($child);
30. }
31.
32. }
33. return $childs;
34. }
35. function getChilds($id=0)
36. {
37. $childArray=array();
38. $childs=$this->getChild($id);
39. foreach ($childs as $child)
40. {
41. $childArray[]=$child;
42. $childArray=array_merge($childArray,$this->getChilds($child));
43. }
44. return $childArray;
45. }
46. function getChild($id)
47. {
48. $childs=array();
49. foreach ($this->cateArray as $child=>$parent)
50. {
51. if ($parent==$id)
52. {
53. $childs[$child]=$child;
54. }
55. }
56. return $childs;
57. }
58. //单线获取父节点
59. function getNodeLever($id)
60. {
61. $parents=array();
62. if (key_exists($this->cateArray[$id],$this->cateArray))
63. {
64. $parents[]=$this->cateArray[$id];
65. $parents=array_merge($parents,$this->getNodeLever($this->cateArray[$id]));
66. }
67. return $parents;
68. }
69. function getLayer($id,$preStr='|-')
70. {
71. return str_repeat($preStr,count($this->getNodeLever($id)));
72. }
73. function getValue ($id)
74. {
75. return $this->data[$id];
76. } // end func
77. }
78.
79. /*$Tree = new Tree("请选择分类");
80. //setNode(目录ID,上级ID,目录名字);
81. $Tree->setNode(1, 0, '目录1');
82. $Tree->setNode(2, 1, '目录2');
83. $Tree->setNode(5, 3, '目录5');
84. $Tree->setNode(3, 0, '目录3');
85. $Tree->setNode(4, 2, '目录4');
86. $Tree->setNode(9, 4, '目录9');
87. $Tree->setNode(6, 2, '目录6');
88. $Tree->setNode(7, 2, '目录7');
89. $Tree->setNode(8, 3, '目录8');
90.
91. //print_r($Tree->getChildsTree(0));
92. //print_r($Tree->getChild(0));
93. //print_r($Tree->getLayer(2));
94.
95. $category = $Tree->getChilds();
96.
97. //遍历输出
98. foreach ($category as $key=>$id)
99. {
100. echo $id.$Tree->getLayer($id, '|-').$Tree->getValue($id)."\n";
101. }*/
102.
103. ?>
简单好用的PHP无限分类