Javascript 如何绘制树结构

Javascript 如何绘制树结构,javascript,php,jquery,html,mysql,Javascript,Php,Jquery,Html,Mysql,我有下面的MySQL记录,所以需要用下面的MySQL数据在PHP中画一个树形结构,这里NULL值代表主父节点 +----------------+----------------+ |id |家长id| +----------------+----------------+ |1 |空| | 2 | 1 | | 3 | 1 | | 4 | 2

我有下面的MySQL记录,所以需要用下面的MySQL数据在PHP中画一个树形结构,这里NULL值代表主父节点


+----------------+----------------+
|id |家长id|
+----------------+----------------+
|1 |空|
| 2              |            1   |
| 3              |            1   |
| 4              |            2   |
| 5              |            3   |
| 6              |            2   |
+----------------+----------------+

输出应为以下格式

请帮帮我

设法


不工作

您可能应该尝试以下方法

1
|->2
|  |->4
|  |->6
|
|->3
|->5

要打印路径,只需执行以下操作:


您已经了解了如何找到从叶节点(没有子节点的节点)到根节点的路径。现在让我们看一下如何向下遍历层次结构——即从根元素开始,根据其层次关系显示所有节点:


你可能需要查看JavaScript,我认为使用PHP不可能绘制树。使用html、JavaScript和css来绘制:你想绘制树还是创建树结构?通过搜索引擎偶然发现了这篇文章。这个答案中的链接已经失效。以下是正确的链接:
             1
           /   \ 
         2      3
        / \    /
       4   6  5     
<?php
function get_path($category_id) 
{
    // look up the parent of this node
    $result = mysql_query("SELECT c1.parent_id,c2.category_name AS     parent_name FROM category AS c1
LEFT JOIN category AS c2 ON c1.parent_id=c2.category_id 
WHERE c1.category_id='$category_id' ");
$row = mysql_fetch_array($result);

   // save the path in this array
    $path = array();

    //continue if this node is not the root node
    if ($row['parent_id']!=NULL) 
    {
        // the last part of the path to node

        end($path);
        $last_key = key($path);
        $key = $last_key==0 ? 0 : $last_key+1;

        $path[$key]['category_id'] = $row['parent_id'];
        $path[$key]['category_name'] = $row['parent_name'];

        $path = array_merge(get_path($row['parent_id']), $path);
    }

   return $path;
}
?>
<?php
for ($i=count($path)-1;$i==0;$i--)
{
     echo $path[$i]['category_name']. '>';
}
?>
<?php
function display_children($category_id, $level) 
{
    // retrieve all children
    $result = mysql_query("SELECT * FROM category WHERE     parent_id='$category_id'");

    // display each child
    while ($row = mysql_fetch_array($result)) 
    {
        // indent and display the title of this child
       // if you want to save the hierarchy, replace the following line with     your code
        echo str_repeat('  ',$level) . $row['category_name'] . "<br/>";

       // call this function again to display this child's children
       display_children($row['category_id'], $level+1);
    }
}
?>