// +---------------------------------------------------------------------- namespace ywxapp\utils; /** * TreeBuilder 类 * * @author ywxapp */ class TreeBuilder { private $data; private $sortedData = []; public function __construct($data) { $this->data = $data; } public function build() { usort($this->data, function($a, $b) { return $a['sort'] <=> $b['sort']; }); $this->buildTree($this->data, 0); return $this->sortedData; } private function buildTree($nodes, $level) { foreach ($nodes as $node) { $node['text'] = str_repeat('| ', $level) . $node['title']; $this->sortedData[] = $node; if (isset($node['children'])) { $this->buildTree($node['children'], $level + 1); } } } private function addChild(&$parent, $child) { foreach ($parent as &$node) { if ($node['id'] == $child['pid']) { if (!isset($node['children'])) { $node['children'] = []; } $node['children'][] = $child; return; } if (isset($node['children'])) { $this->addChild($node['children'], $child); } } } function generateCategoryList($categories, $parentId = 0, $level = 0) { $html = ''; foreach ($categories as $category) { if ($category['parent_id'] == $parentId) { $html .= ''; } } return $html; } } // 示例数据 // $data = [ // ['id' => 1, 'title' => '动态', 'name' => 'news', 'pid' => 0, 'sort' => 2], // ['id' => 2, 'title' => '测试分类', 'name' => 'test', 'pid' => 0, 'sort' => 1], // ['id' => 3, 'title' => '官方动态', 'name' => 'gov', 'pid' => 1, 'sort' => 1], // ]; // $treeBuilder = new TreeBuilder($data); // $sortedData = $treeBuilder->build(); // print_r($sortedData);