TreeModel.class.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Common\Model;
  3. class TreeModel
  4. {
  5. /**
  6. * 将格式数组转换为树
  7. *
  8. * @param array $list
  9. * @param integer $level 进行递归时传递用的参数
  10. */
  11. private $formatTree;
  12. public function toTree($list = NULL, $pk = 'id', $pid = 'pid', $child = '_child')
  13. {
  14. if (null === $list) {
  15. $list = &$this->dataList;
  16. }
  17. $tree = array();
  18. if (is_array($list)) {
  19. $refer = array();
  20. foreach ($list as $key => $data) {
  21. $_key = (is_object($data) ? $data->$pk : $data[$pk]);
  22. $refer[$_key] = &$list[$key];
  23. }
  24. foreach ($list as $key => $data) {
  25. $parentId = (is_object($data) ? $data->$pid : $data[$pid]);
  26. $is_exist_pid = false;
  27. foreach ($refer as $k => $v) {
  28. if ($parentId == $k) {
  29. $is_exist_pid = true;
  30. break;
  31. }
  32. }
  33. if ($is_exist_pid) {
  34. if (isset($refer[$parentId])) {
  35. $parent = &$refer[$parentId];
  36. $parent[$child][] = &$list[$key];
  37. }
  38. }
  39. else {
  40. $tree[] = &$list[$key];
  41. }
  42. }
  43. }
  44. return $tree;
  45. }
  46. private function _toFormatTree($list, $level = 0, $title = 'title')
  47. {
  48. foreach ($list as $key => $val) {
  49. $tmp_str = str_repeat('&nbsp;', $level * 2);
  50. $tmp_str .= '└';
  51. $val['level'] = $level;
  52. $val['title_show'] = ($level == 0 ? $val[$title] . '&nbsp;' : $tmp_str . $val[$title] . '&nbsp;');
  53. if (!array_key_exists('_child', $val)) {
  54. array_push($this->formatTree, $val);
  55. }
  56. else {
  57. $tmp_ary = $val['_child'];
  58. unset($val['_child']);
  59. array_push($this->formatTree, $val);
  60. $this->_toFormatTree($tmp_ary, $level + 1, $title);
  61. }
  62. }
  63. return NULL;
  64. }
  65. public function toFormatTree($list, $title = 'title', $pk = 'id', $pid = 'pid', $root = 0)
  66. {
  67. $list = list_to_tree($list, $pk, $pid, '_child', $root);
  68. $this->formatTree = array();
  69. $this->_toFormatTree($list, 0, $title);
  70. return $this->formatTree;
  71. }
  72. }
  73. ?>