2

go 语言,如何实现这样的嵌套循环?

 2 years ago
source link: https://www.v2ex.com/t/855279
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Go 编程语言

go 语言,如何实现这样的嵌套循环?

  olddogs · 12 小时 15 分钟前 · 1172 次点击

请问在数据库里面查询出来的列表,如何循环出这样的分组结构呢?

"manage": {
   "ent": {
   "export": true,
   "get": true,
   "plan": true
  }
},
"oa": {
   "user": {
     "add": true,
     "addDept": true,
     "addUser": true,
     "get": true,
     "plan": true
  }
}

用 php 可以通过循环,这样拼接,但是用 go 就玩不好了

$newList[$v['name']][$v1['name']][$v2['name']] = true

第 1 条附言  ·  11 小时 31 分钟前

类似这样的数据 ,

{
  "id": 1,
  "name": "manage",
  "parent_id": 0,
  "children": [
    {
      "id": 101,
      "name": "ent",
      "parent_id": 1,
      "children": [
        {
          "id": 102,
          "name": "get",
          "parent_id": 101
        },
        {
          "id": 103,
          "name": "edit",
          "parent_id": 101
        }
      ]
    }
  ]
}

我现在的写法,但是这样有问题,这样没办法按照children分组,麻烦帮忙看看


func ruleListToObj(rules []Rule) (list map[string]map[string]map[string]bool) {
	root := make(map[string]map[string]map[string]bool)
	module := make(map[string]map[string]bool)
	view := make(map[string]bool)

	for _, v := range rules {
		root[v.Name] = module
		if len(v.Children) > 0 {
			for _, vv := range v.Children {
				module[vv.Name] = view
				if len(vv.Children) > 0 {
					for _, vvv := range v.Children {
						view[vvv.Name] = true
					}
				}
			}
		}
	}
	return root
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK