数据结构:create table web_class ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(255) NOT NULL, --名称
"bid" integer, --上级ID)数据库数据:{id:1, name:'名称1', bid:0}{id:2, name:'名称2', bid:0}{id:3, name:'名称3', bid:1}{id:4, name:'名称4', bid:1}{id:5, name:'名称5', bid:3}{id:6, name:'名称6', bid:5}...需要实现的树形菜单(类似如下):[{'bid':0,'id':1,'name':'名称1', 'son':[
{'bid':1,'id':3,'name':'名称3', 'son':[
{'bid':3,'id':5,'name':'名称5', 'son':[
{'bid':3,'id':6,'name':'名称6','son':[]}
]
}
]
},
{'bid':1,'id':4,'name':'名称4','son':[]}
]
},
{'bid':0,'id':2,'name':'名称2','son':[]}]如能讲解下原理最好了。
2 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
我自己研究写出来的一个函数(线型菜单转树形菜单):
def xTree(datas):
lists=[] tree={}
parent_id=''
for i in datas:
item=i tree[item['id']]=item
root=None for i in datas:
obj=i if not obj['bid']:
root=tree[obj['id']]
lists.append(root) else:
parent_id=obj['bid'] if 'children' not in tree[parent_id]:
tree[parent_id]['children']=[] tree[parent_id]['children'].append(tree[obj['id']])
return lists
print(xTree(data))添加回答
举报
0/150
提交
取消
