c#
/// <summary>
/// 递归创建小程序类目树
/// </summary>
public List<MiniCategorysTree> BuildMenuTree(MiniCategorysTree node)
{
//条件:item.parent_category_id == node.CategoryId
List<MiniCategorysTree> childrenCategorys = MiniCateGoryList.Where(item => item.parent_category_id == node.CategoryId)
.Select(item => new MiniCategorysTree()
{
Name = item.category_name,
CategoryId = item.category_id,
HasChild = item.has_child,
NeedLicense = item?.need_license,
NeedOutDoorPic = item?.need_out_door_pic,
NeedSpecialLicense = item?.need_special_license,
})
.ToList();
node.ChildrenCategorys = childrenCategorys;
for (int i = 0; i < childrenCategorys.Count; i++)
{
//递归调用创建子节点
if (childrenCategorys[i].HasChild == true)
childrenCategorys[i].ChildrenCategorys = BuildMenuTree(childrenCategorys[i]);
}
return childrenCategorys;
}
在需要用到的地方调用:
MiniCategorysTree nodeRoot = new MiniCategorysTree()
{
Name = "根节点",
CategoryId = "0",
HasChild = true,
NeedLicense = false,
NeedOutDoorPic = false,
NeedSpecialLicense = false,
};
List<MiniCategorysTree> miniCategorysTree = AppService.BuildMenuTree(nodeRoot);
miniCategorysTree的 结果:
参考:https://www.cnblogs.com/xwei/p/6166320.html
php
class foo{
static $array;
public function __construct()
{
self::$array = [
['id' => 1,'parent_id'=>0],
['id' => 2,'parent_id'=>1],
['id' => 3,'parent_id'=>1],
['id' => 4,'parent_id'=>1],
['id' => 5,'parent_id'=>1],
['id' => 6,'parent_id'=>0],
['id' => 7,'parent_id'=>5],
];
}
public static function buildTree($node){
foreach(self::$array as $key => $item){
if($node['nodeId'] == $item['parent_id']){
array_push($node['childrenNodes'], [
'nodeId' => $item['id'],
'parent_id' =>$item['parent_id'],
'hasNode' => false,
'childrenNodes' => [],
]);
unset(self::$array[$key]);
}
}
if(count($node['childrenNodes'])) $node['hasNode'] = true;
foreach($node['childrenNodes'] as $key => &$cNode){
$cNode = self::buildTree($cNode);
}
return $node;
}
public function getTree()
{
$rootNode = [
'nodeId' => 0,
'parent_id' =>'-1',
'hasNode' => false,
'childrenNodes' => [],
];
return self::buildTree($rootNode);
}
}
$foo = new foo();
print_r(json_encode($foo->getTree()));