0
0

Phptree.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace tools;
  3. /**
  4. * @name PHPTree
  5. * @author crazymus < QQ:291445576 >
  6. * @des PHP生成树形结构,无限多级分类
  7. * @version 1.2.0
  8. * @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  9. * @updated 2015-08-26
  10. */
  11. class Phptree
  12. {
  13. protected static $config = array(
  14. /* 主键 */
  15. 'primary_key' => 'id',
  16. /* 父键 */
  17. 'parent_key' => 'parent_id',
  18. /* 展开属性 */
  19. 'expanded_key' => 'expanded',
  20. /* 叶子节点属性 */
  21. 'leaf_key' => 'leaf',
  22. /* 孩子节点属性 */
  23. 'children_key' => 'children',
  24. /* 是否展开子节点 */
  25. 'expanded' => false
  26. );
  27. /* 结果集 */
  28. protected static $result = array();
  29. /* 层次暂存 */
  30. protected static $level = array();
  31. /**
  32. * @name 生成树形结构
  33. * @param array 二维数组
  34. * @return mixed 多维数组
  35. */
  36. public static function makeTree($data, $options=array())
  37. {
  38. $dataset = self::buildData($data, $options);
  39. $r = self::makeTreeCore(0, $dataset, 'normal');
  40. return $r;
  41. }
  42. /* 生成线性结构, 便于HTML输出, 参数同上 */
  43. public static function makeTreeForHtml($data, $options=array())
  44. {
  45. $dataset = self::buildData($data, $options);
  46. $r = self::makeTreeCore(0, $dataset, 'linear');
  47. return $r;
  48. }
  49. /* 格式化数据, 私有方法 */
  50. private static function buildData($data, $options)
  51. {
  52. $config = array_merge(self::$config, $options);
  53. self::$config = $config;
  54. extract($config);
  55. $r = array();
  56. foreach ($data as $item) {
  57. $id = $item[$primary_key];
  58. $parent_id = $item[$parent_key];
  59. $r[$parent_id][$id] = $item;
  60. }
  61. return $r;
  62. }
  63. /* 生成树核心, 私有方法 */
  64. private static function makeTreeCore($index, $data, $type='linear')
  65. {
  66. extract(self::$config);
  67. foreach ($data[$index] as $id=>$item) {
  68. if ($type=='normal') {
  69. if (isset($data[$id])) {
  70. $item[$expanded_key]= self::$config['expanded'];
  71. $item[$children_key]= self::makeTreeCore($id, $data, $type);
  72. } else {
  73. $item[$leaf_key]= true;
  74. }
  75. $r[] = $item;
  76. } elseif ($type=='linear') {
  77. $parent_id = $item[$parent_key];
  78. self::$level[$id] = $index==0?0:self::$level[$parent_id]+1;
  79. $item['level'] = self::$level[$id];
  80. self::$result[] = $item;
  81. if (isset($data[$id])) {
  82. self::makeTreeCore($id, $data, $type);
  83. }
  84. $r = self::$result;
  85. }
  86. }
  87. return $r;
  88. }
  89. }