V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
dong568789

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

  •  
  •   dong568789 · Dec 21, 2021 · 3509 views
    This topic created in 1597 days ago, the information mentioned may be changed or developed.
        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);
    
    Supplement 1  ·  Dec 23, 2021
    可能没有描述的清楚,这个是 php 生成树形结构的代码,我是想 go 能不能也使用这种引用赋值的方式来实现相同的功能。
    11 replies    2021-12-24 20:08:25 +08:00
    xjqxz2
        1
    xjqxz2  
       Dec 21, 2021
    你把 Array 想成 Map[string]interface{} :逃~
    dong568789
        2
    dong568789  
    OP
       Dec 21, 2021
    @xjqxz2 用 map ,后面还要涉及到排序,挺难搞的。
    object123
        3
    object123  
       Dec 21, 2021
    生成 tree 结构,不一样写吗
    moliliang
        4
    moliliang  
       Dec 21, 2021
    不复杂呀,慢慢琢磨琢磨~
    ThanksSirAlex
        5
    ThanksSirAlex  
       Dec 21, 2021   ❤️ 1
    简单的就用 map ,不想用 map 就自己定义一个 struct
    akagishigeru
        6
    akagishigeru  
       Dec 21, 2021 via iPhone
    树啊,结构体
    2i2Re2PLMaDnghL
        7
    2i2Re2PLMaDnghL  
       Dec 22, 2021
    php kv 对是保序的吗?
    那样的话可以考虑一下 struct {key string; value interface{}}[] (逃
    yrj
        8
    yrj  
       Dec 22, 2021 via iPad
    这种序列化分类的功能,应该挺常见的吧,不会写的话,自己网上搜一下吧。
    sanggao
        10
    sanggao  
       Dec 24, 2021
    golang 真是表达力很弱的语言,不适合拿来做业务开发
    admpubcom
        11
    admpubcom  
       Dec 24, 2021 via iPhone
    自己写了一个,可以参考: https://github.com/coscms/tree
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5378 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 99ms · UTC 09:37 · PVG 17:37 · LAX 02:37 · JFK 05:37
    ♥ Do have faith in what you're doing.