BuildTree.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace common\util;
  3. class BuildTree
  4. {
  5. /**
  6. * @param $nodes
  7. * @return Tree|mixed|null
  8. */
  9. public static function build($nodes)
  10. {
  11. if ($nodes == null) {
  12. return null;
  13. }
  14. $topNodes = [];
  15. foreach ($nodes as $children) {
  16. /** @var Tree $children */
  17. $pid = $children->getParentId();
  18. if ($pid == null || $pid == 0) {
  19. $topNodes[] = $children;
  20. continue;
  21. }
  22. foreach ($nodes as $parent) {
  23. /** @var Tree $parent */
  24. $id = $parent->getId();
  25. if ($id != null && $id == $pid) {
  26. $parent->addChildren($children);
  27. $children->setHasParent(true);
  28. $parent->setHasChildren(true);
  29. continue;
  30. }
  31. }
  32. }
  33. $root = new Tree();
  34. if (sizeof($topNodes) == 1) {
  35. $root = $topNodes[0];
  36. } else {
  37. $root->setId("-1");
  38. $root->setParentId("");
  39. $root->setHasParent(false);
  40. $root->setHasChildren(true);
  41. $root->setChecked(true);
  42. $root->setChildren($topNodes);
  43. $root->setText("顶级节点");
  44. $root->setState(["opened" => true]);
  45. }
  46. return $root;
  47. }
  48. }