87 lines
2.6 KiB
PHP
87 lines
2.6 KiB
PHP
<?php
|
|
// +----------------------------------------------------------------------
|
|
// | YwxApp [ WE CAN DO IT JUST THINK ]
|
|
// +----------------------------------------------------------------------
|
|
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
|
|
// +----------------------------------------------------------------------
|
|
// | Author: ywxapp<admin@ywxapp.cn>
|
|
// +----------------------------------------------------------------------
|
|
namespace ywxapp\utils;
|
|
/**
|
|
* TreeBuilder 类
|
|
*
|
|
* @author ywxapp <admin@ywxapp.cn>
|
|
*/
|
|
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 .= '<ul>';
|
|
$html .= '<li style="margin-left: ' . ($level * 20) . 'px;">' . $category['name'];
|
|
$html .= generateCategoryList($categories, $category['id'], $level + 1); // 递归调用
|
|
$html .= '</li>';
|
|
$html .= '</ul>';
|
|
}
|
|
}
|
|
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);
|