无法在PHP中的遍历预序中显示所有树

2024-03-12

我的数据库中有一个表,其中包含许多家谱树。

-----------------------------
- id  name              parent_id
-----------------------------
- 1   grandfather       NULL
- 2   father            1
- 3   uncle             1
- 4   son               2
- 5   brother           2
- 6   cousin's dauther  7
- 7   cousin            8
- 8   auntie            1

问题是由于边缘情况我无法显示所有名称:

-当我有一个人的parent_id大于其父母的parent_id时 (见表弟的女儿)

我使用此查询来获取表:

    $sql = "SELECT p1.id, p1.name, p1.parent_id FROM pariente p1 
    ORDER BY p1.parent_id";
    $result = $conn->query($sql);

问题是,如果我使用“ORDER BY Parent_id”,“cousin's dauther”将不会显示,如果我使用“ORDER BY id”,“cousin”将不会显示。

我使用这个函数将树制作成数组并绘制它:

        function make_tree($data, $root) {
            $tree = [];
            foreach ($data as $node) {
                insert($tree, $node);
            }

            return $tree;
        }

        function insert(&$root, &$node) {
            if (!$root) {
                $root = $node;
            }
            else if ($root["id"] === $node["parent_id"]) {
                $root["children"][] = $node;
            }
            else if (array_key_exists("children", $root)) {
                foreach ($root["children"] as &$c) {
                    if (insert($c, $node)) {
                        break;
                    }
                }
            }
        }

        function preorder2(&$root) {
            if ($root) {
                echo "<li>";
                echo $root["name"];

                if (array_key_exists("children", $root)) {
                    echo "<ul>";
                    foreach ($root["children"] as $c) {
                        preorder2($c);
                    }
                    echo "</ul>";
                }
                echo "</li>";
            }
        }
    ?>

在我使用它来调用函数之后:

<div>

<?php
while( $row = mysqli_fetch_assoc( $result)){
    $resguard[] = $row;
}
    $tree = make_tree($resguard);
    preorder2($tree);
?>
</div>

我曾经遇到过类似的问题,这就是我解决它的方法。

  1. 迭代数据集,将每个节点放入数组中,并跟踪要成为根节点的节点。

  2. 迭代数组。对于每个parent_id不为null的节点,通过id查找父节点,并将当前节点添加为子节点。构建树时无需使用递归。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在PHP中的遍历预序中显示所有树 的相关文章

随机推荐