【问题标题】:how to php mysql draw a tree structurephp mysql如何绘制树形结构
【发布时间】:2017-09-13 04:21:59
【问题描述】:

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

+----------------+----------------+ | id | parent_id | +----------------+----------------+ | 1 | NULL| | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 3 | | 6 | 2 | +----------------+----------------+

输出应为以下格式

             1
           /   \ 
         2      3
        / \    /
       4   6  5     

请帮帮我。

尝试https://www.daniweb.com/programming/web-development/threads/231905/binary-tree-using-php-mysql#post1027437

不工作

【问题讨论】:

  • 您可能需要查看 JavaScript 我认为使用 PHP 绘制树是不可能的。
  • 使用html、javascript和css来绘制
  • 试用:phpflow tutorial
  • 你想画树还是创建树结构?

标签: javascript php jquery html mysql


【解决方案1】:
<?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);
    }
}
?>

http://www.phpbuilder.com/articles/databases/mysql/handling-hierarchical-data-in-mysql-and-php.html

【讨论】:

【解决方案2】:

你应该尝试类似的东西

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

这比传统的二元图更容易实现。并且可以在水平和垂直方向上轻松缩放,不会出现任何 UI 问题。

鉴于数据集很大,上下图需要您进行更多计算,以根据每个节点拥有的子节点数量来获取每个节点之间的距离。 此外,您可能需要进行额外的计算以使它们适当地居中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多