
function tree(array $items) { $ids = []; foreach ($items as $item) { if ($item['id'] == $item['pid']) continue; //如果父 ID 等于自己,避免死循环,跳过 $ids[] = $item['id']; $items[ ($item['pid']) ][ 'children' ][ ($item['id']) ] = &$items[ ($item['id']) ]; } $result = Arr::except($items, $ids); return count($result) === 1 ? Arr::get(array_pop($result), 'children', []) : $result; } $items = [ ['id' => 0, 'name' => 'none', 'pid' => 0], ['id' => 1, 'name' => 'test', 'pid' => 0], ['id' => 2, 'name' => 'test1', 'pid' => 1], ['id' => 3, 'name' => 'test2', 'pid' => 1], ]; tree($items); 1 xjqxz2 2021-12-21 16:35:42 +08:00 你把 Array 想成 Map[string]interface{} :逃~ |
2 dong568789 OP @xjqxz2 用 map ,后面还要涉及到排序,挺难搞的。 |
3 object123 2021-12-21 17:00:31 +08:00 生成 tree 结构,不一样写吗 |
4 moliliang 2021-12-21 17:33:52 +08:00 不复杂呀,慢慢琢磨琢磨~ |
5 ThanksSirAlex 2021-12-21 17:40:17 +08:00 简单的就用 map ,不想用 map 就自己定义一个 struct |
6 akagishigeru 2021-12-21 18:45:06 +08:00 via iPhone 树啊,结构体 |
7 2i2Re2PLMaDnghL 2021-12-22 10:16:19 +08:00 php kv 对是保序的吗? 那样的话可以考虑一下 struct {key string; value interface{}}[] (逃 |
8 yrj 2021-12-22 13:20:24 +08:00 via iPad 这种序列化分类的功能,应该挺常见的吧,不会写的话,自己网上搜一下吧。 |
9 chengxiao 2021-12-22 17:26:44 +08:00 |
10 sanggao 2021-12-24 10:39:00 +08:00 golang 真是表达力很弱的语言,不适合拿来做业务开发 |
11 admpubcom 2021-12-24 20:08:25 +08:00 via iPhone 自己写了一个,可以参考: https://github.com/coscms/tree |