You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

二叉树邻接表结构下获取父节点子节点并展示层级的问题

修复二叉树邻接表子节点层级检索问题

我来帮你搞定这个问题!咱们先分析下原有代码的问题,再给出修复后的方案:

问题根源

你的原有代码(包括更新后的版本)都犯了同一个核心错误:只递归存储了子节点的子树,却没有把当前子节点的自身数据包含进去。这就导致当节点没有子节点时,返回的是空数组,最终整个结果里全是空的嵌套结构,完全看不到实际的节点信息。

修复后的代码

下面的代码会先保留每个子节点的自身数据(比如idsponsor_idposition),再递归获取它的子节点并作为children字段关联到当前节点上,这样就能形成清晰的层级结构:

public function get_all_downlines($id){ 
    $tree = array(); 
    // 获取当前父节点的所有直接子节点
    $this->db->where('sponsor_id', $id); 
    $query = $this->db->get('users'); 
    $children = $query->result_array(); 

    foreach($children as $child){ 
        // 保留当前子节点的所有字段信息
        $node = $child;
        // 递归获取该子节点的所有下线,作为它的子节点集合
        $node['children'] = $this->get_all_downlines($child['id']);
        // 将完整的节点信息加入到树结构中
        $tree[] = $node;
    } 

    return $tree; 
}

示例输出

假设父节点id=1有2个直接子节点,其中一个子节点id=2又有1个子节点,返回的数组结构会是这样的(清晰展示层级关系):

Array (
    [0] => Array (
        'id' => 2,
        'sponsor_id' => 1,
        'position' => 'left',
        'children' => Array (
            [0] => Array (
                'id' => 4,
                'sponsor_id' => 2,
                'position' => 'right',
                'children' => Array ( )
            )
        )
    ),
    [1] => Array (
        'id' => 3,
        'sponsor_id' => 1,
        'position' => 'right',
        'children' => Array ( )
    )
)

可选:用节点ID作为数组键

如果你希望用子节点的id作为数组的键(而非默认的数字索引),可以稍微调整代码:

public function get_all_downlines($id){ 
    $tree = array(); 
    $this->db->where('sponsor_id', $id); 
    $query = $this->db->get('users'); 
    $children = $query->result_array(); 

    foreach($children as $child){ 
        $node = $child;
        $node['children'] = $this->get_all_downlines($child['id']);
        // 以子节点ID作为数组键
        $tree[$child['id']] = $node;
    } 

    return $tree; 
}

这样输出的数组会以节点ID为键,更方便直接通过ID定位节点。

内容的提问来源于stack exchange,提问作者Okechukwu Mba

火山引擎 最新活动