天天看点

无限级分类

无限级分类

第一种处理(递归):

将数据如下输出:

上海
-青浦
-浦东
--张江
北京
-昌平      
data=[
    {"cat_id":3,"name":"青浦","parent_id":1},
    {"cat_id": 2, "name": "张江", "parent_id": 4},
    {"cat_id":4,"name":"浦东","parent_id":1},
    {"cat_id":5, "name": "北京", "parent_id": 0},
    {"cat_id":6, "name": "昌平", "parent_id": 5},
    {"cat_id": 1, "name": "上海", "parent_id": 0},
]

res = []
def get_son(data, level=0, parent_id=0):
    for item in data:
        # 如果当前循环的parent_id=parent_id,将level等级添加到列表中
        if item['parent_id'] == parent_id:
            item['level'] = level
            res.append(item)
            # 循环所有的数据
            get_son(data, level+1, parent_id=item['cat_id'])
    return res

t = get_son(data)

for i in t:
    print(i['level']*'-', i['name'])
    
#  北京
# - 昌平
#  上海
# - 青浦
# - 浦东
# -- 张江      

第二种树的行式:

需求如下:

将data 数据变成lists

lists=[{'cat_id': 5, 'name': '北京', 'parent_id': 0, 'level': 0, 'children':
    [{'cat_id': 6, 'name': '昌平', 'parent_id': 5, 'level': 1}]},

   {'cat_id': 1, 'name': '上海', 'parent_id': 0, 'level': 0, 'children':
       [{'cat_id': 3, 'name': '青浦', 'parent_id': 1, 'level': 1},
        {'cat_id': 4, 'name': '浦东', 'parent_id': 1, 'level': 1, 'children':
            [{'cat_id': 2, 'name': '张江', 'parent_id': 4, 'level': 2}]}]}]      
# 2、变成这种格式
'''
data1 = [
    {"cat_id": 1, "name": "上海", "parent_id": 0,
          "children":[
              {"cat_id":4,"name":"浦东","parent_id":1,
               "children":[
                  {"cat_id": 2, "name": "张江", "parent_id": 4},
               ]
              }
          ]
          },
         ]

'''


def get_tree(data):
    lists = []
    tree = {}
    for i in data:
        tree[i['cat_id']] = i  # 给它变成k,v的形式,k就是cat_id,v就是这个字典对象
    for item in data:
        if item['parent_id'] == 0:  # 说明它是根节点
            lists.append(tree[item['cat_id']])  # 将根节点的字典添加到列表中
        else:
            if 'children' not in tree[item['parent_id']]:  # 判断每一个字典(对象)有没有属于自己的儿子
                tree[item['parent_id']]['children'] = []  # 没有就给字典(该对象)添加一个新的名为children的key,并且赋值空列表
            tree[item['parent_id']]['children'].append(tree[item['cat_id']]) # 把儿子对象添加进去

    return lists


# item=为一个个的字典对象
#     {"cat_id":3,"name":"青浦","parent_id":1},
#     {"cat_id": 2, "name": "张江", "parent_id": 4},
#     {"cat_id":4,"name":"浦东","parent_id":1},
#     {"cat_id":5, "name": "北京", "parent_id": 0},
#     {"cat_id":6, "name": "昌平", "parent_id": 5},
#     {"cat_id": 1, "name": "上海", "parent_id": 0},


# tree={
#     3:{"cat_id":3,"name":"青浦","parent_id":1},
#     2:{"cat_id": 2, "name": "张江", "parent_id": 4},
#     4:{"cat_id":4,"name":"浦东","parent_id":1},
#     5:{"cat_id":5, "name": "北京", "parent_id": 0},
#     6:{"cat_id":6, "name": "昌平", "parent_id": 5},
#     1:{"cat_id": 1, "name": "上海", "parent_id": 0},
# }