这段 PHP 代码如何用 go 来实现?

2021-12-21 16:06:30 +08:00
 dong568789
    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);
2488 次点击
所在节点    Go 编程语言
11 条回复
xjqxz2
2021-12-21 16:35:42 +08:00
你把 Array 想成 Map[string]interface{} :逃~
dong568789
2021-12-21 16:46:43 +08:00
@xjqxz2 用 map ,后面还要涉及到排序,挺难搞的。
object123
2021-12-21 17:00:31 +08:00
生成 tree 结构,不一样写吗
moliliang
2021-12-21 17:33:52 +08:00
不复杂呀,慢慢琢磨琢磨~
ThanksSirAlex
2021-12-21 17:40:17 +08:00
简单的就用 map ,不想用 map 就自己定义一个 struct
JaguarJack
2021-12-21 18:45:06 +08:00
树啊,结构体
2i2Re2PLMaDnghL
2021-12-22 10:16:19 +08:00
php kv 对是保序的吗?
那样的话可以考虑一下 struct {key string; value interface{}}[] (逃
yrj
2021-12-22 13:20:24 +08:00
这种序列化分类的功能,应该挺常见的吧,不会写的话,自己网上搜一下吧。
chengxiao
2021-12-22 17:26:44 +08:00
sanggao
2021-12-24 10:39:00 +08:00
golang 真是表达力很弱的语言,不适合拿来做业务开发
admpubcom
2021-12-24 20:08:25 +08:00
自己写了一个,可以参考: https://github.com/coscms/tree

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/823558

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX