【问题标题】:PHP mysql Tree Child count and List All Child node level wisePHP mysql Tree Child count and List All Child node level wise
【发布时间】:2021-04-26 16:06:49
【问题描述】:

我有一棵像
这样的树
我想要 requeted ID 的输出,例如 Admin


我的表结构是

我有一个方法可以按级别返回子计数,但我也想按级别返回子列表,并按级别返回子列表,例如需要第二张图像输出。

function childCountLevelWise($conn,$ID, $level){
if ($level>14){
    $count = array(0=>0); 
    return $count;
}
$sql="select * from user_my_tree t where t.parent_ID=".$ID;
$result=returnResults($conn,$sql);
if ($result==null){
    $count = array(0=>0); 
}
else{
    $count = array(0=>0);
    foreach($result as $key=>$row)
    {   
        $count[0]++;
        $children=childCountLevelWise($conn,$row['ID'], $level+1);
        $index=1;
        foreach ($children as $child)
        {
            if ($child==0)
                continue;
            if (isset($count[$index]))
                $count[$index] += $child;
            else    
                $count[$index] = $child;
                $index++;
        }    
    }    
}
return $count; 

}

【问题讨论】:

标签: php mysql tree treeview


【解决方案1】:

听起来您只是想要一种计算嵌套集的方法,我可以在不使用数据库的情况下通过以下代码重现您的示例:

function returnResults($parent)
{
    switch ($parent) {
        case 'root':
            return ['vijay', 'suresh', 'mukesh'];
        case 'vijay':
            return ['manish', 'rohan', 'manu'];
        case 'manish':
            return ['rinku', 'raja', 'vijay2'];
        default:
            return [];
    }
}

function childCountLevelWise($parent, $level, &$result)
{
    $result[$level] = empty($result[$level]) ? [] : $result[$level]; // init array
    if ($level > 14) {
        return; // ignore levels over 14
    }

    $levelResults = returnResults($parent); // get results for this parent
    $result[$level] = array_merge($result[$level], $levelResults); // add to results for this level
    foreach ($levelResults as $child) {
        childCountLevelWise($child, $level + 1, $result); // check for each child at this level
    }
}

调用它并用这段代码打印结果

childCountLevelWise('root', 0, $result);

// print result
foreach ($result as $level => $people) {
    if (!empty($people)) {
        printf('Result for level %d: %s', $level, implode(',', $people));
        echo "\n";
    }
}

将导致:

Result for level 0: vijay,suresh,mukesh
Result for level 1: manish,rohan,manu
Result for level 2: rinku,raja,vijay2

从那里我认为修改我的示例中的returnResults 函数以查询数据库应该足够简单,尽管如果您在很多结果上使用它,您可能需要考虑它的性能成本。已经有很好的解决方案可以在数据库中使用树结构,例如 Doctrine 中的Nested Set

【讨论】:

    猜你喜欢
    • 2015-04-06
    • 2011-07-20
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多