12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- namespace common\util;
- class BuildTree
- {
- /**
- * @param $nodes
- * @return Tree|mixed|null
- */
- public static function build($nodes)
- {
- if ($nodes == null) {
- return null;
- }
- $topNodes = [];
- foreach ($nodes as $children) {
- /** @var Tree $children */
- $pid = $children->getParentId();
- if ($pid == null || $pid == 0) {
- $topNodes[] = $children;
- continue;
- }
- foreach ($nodes as $parent) {
- /** @var Tree $parent */
- $id = $parent->getId();
- if ($id != null && $id == $pid) {
- $parent->addChildren($children);
- $children->setHasParent(true);
- $parent->setHasChildren(true);
- continue;
- }
- }
- }
- $root = new Tree();
- if (sizeof($topNodes) == 1) {
- $root = $topNodes[0];
- } else {
- $root->setId("-1");
- $root->setParentId("");
- $root->setHasParent(false);
- $root->setHasChildren(true);
- $root->setChecked(true);
- $root->setChildren($topNodes);
- $root->setText("顶级节点");
- $root->setState(["opened" => true]);
- }
- return $root;
- }
- }
|