php - 使用 PHP MySQL 显示特定 child ID 的 parent

标签 php mysql tree

我正在尝试在链数据中显示特定 child 的所有 parent ,如下图所示

first image here

对于这张表的数据

second image here

到目前为止,我已经尝试过以下方法:

// for this one i am getting a indefinite loop

public function buildBinaryTree($user_id)
{
    $pictures = [];

    $p_info = $this->memberRepository->getMemberInfo($user_id);
    $p_id = $p_info->member_id;

    if(empty($p_id)){
        return;
    }

    $children = $this->buildBinaryTree($p_id);

    if ($children) {
        echo "child ". $p_id."</br>";
    }
}

public function buildTree($all_members, $user_id)
{
    $pictures = [];

    foreach ($all_members as $item) {

        if ($item->member_id == $user_id) {

            $pictures[] = [
                'member_id'      => $item->member_id,
                'referrar_id'     => $item->user_id
            ];

            $children = $this->buildTree($all_members, $item->user_id);

            if ($children) {
                $item['children'] = $children;
            }            
        }
    }

    return $pictures;

}

但我仍然不知道如何获取数据:

8->7->6->5->4->3->2->1->0

a[0]{
   'member_id' => 8,
   'user_id' => 7
},
a[1]{
   'member_id' => 7,
   'user_id' => 6
},

我正在寻找使用 PHP MySQL 在数据链中查找特定子 ID 的所有顶级父级的最佳方法?

最佳答案

分层数据可能会很棘手,尤其是如果您不能保证它的深度永远不会超过 2 层或类似的东西。

之前的回答可能会有帮助:https://stackoverflow.com/a/990536/7595840

您会从上面的链接在嵌套集中找到一些,但我很幸运地使用 Modified Preorder Tree Traversal Algorithm 重构了我的数据模型,使其具有更复杂的层次结构。 .它确实需要稍微重组您的数据,但对于像您这样的情况,它可以非常有助于构建层次结构树的完整表示并且非常高效。

关于php - 使用 PHP MySQL 显示特定 child ID 的 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42356999/

相关文章:

mysql - mysql函数中的ibatis和定界符

mysql - 继续获取 'reading initial communication packet' 的 MySQL 错误,系统错误 : 111

php - MySQL查询后使用PHP输出唯一数据

sql - 在左表中获取没有开销的大树

javacc - 解析树+结果

php - ZendService\WindowsAzure 与 zf2

php - 事务中的多个查询并使用 php 提交/回滚

php - 如何使用 PHP 添加 "No results found"消息?

php - 如何从存储在数据库中的图像中获取图像的高度和宽度?

algorithm - 二叉树遍历的栈帧