如何从mysql数据中绘制php中的树结构?

时间:2014-10-08 06:31:25

标签: javascript php mysql css

我有以下mysql记录,所以需要在php中使用下面的mysql数据绘制树结构,这里NULL值代表主要的父节点,

+----------------+----------------+
| child          | parent         |
+----------------+----------------+
| 216            |            103 |
| 217            |            216 |
| 88             |            216 |
| 102            |           NULL |
| 103            |            102 |
| 104            |            102 |
+----------------+----------------+

输出应为格式

               102
              /   \ 
            103    104
            /
          216
         /  \
       217   218

请帮帮我

1 个答案:

答案 0 :(得分:1)

为子父级创建数组的函数:

function parseTree($tree, $root = null) {
    $return = array();
    # Traverse the tree and search for direct children of the root
    foreach($tree as $child => $parent) {
        # A direct child is found
        if($parent == $root) {
            # Remove item from tree (we don't need to traverse this again)
            unset($tree[$child]);
            # Append the child into result array and parse its children
            $return[] = array(
                'name' => $child,
                'children' => parseTree($tree, $child)
            );
        }
    }
    return empty($return) ? null : $return;    
}

输出:

function printtree($tree) {
    if(!is_null($tree) && count($tree) > 0) {
        echo '<ul>';
        foreach($tree as $node) {
            echo '<li>'.$node['name'];
            printTree($node['children']);
            echo '</li>';
        }
        echo '</ul>';
    }
}

完整的PHP脚本:

<?php
$arr = array(
'216'=>103,
'217'=>216,
'88'=>216,
'102'=>NULL,
'103'=>102,
'104'=>102
);
function parseTree($tree, $root = null) {
    $return = array();
    # Traverse the tree and search for direct children of the root
    foreach($tree as $child => $parent) {
        # A direct child is found
        if($parent == $root) {
            # Remove item from tree (we don't need to traverse this again)
            unset($tree[$child]);
            # Append the child into result array and parse its children
            $return[] = array(
                'name' => $child,
                'children' => parseTree($tree, $child)
            );
        }
    }
    return empty($return) ? null : $return;    
}

function printtree($tree) {
    if(!is_null($tree) && count($tree) > 0) {
        echo '<ul>';
        foreach($tree as $b) {
            echo '<li>'.$b['name'];
            printtree($b['children']);
            echo '</li>';
        }
        echo '</ul>';
    }
}

printtree(parseTree($arr));
?>

输出:

  • 102
    • 103
      • 216
        • 217
        • 88
    • 104

可以使用的小CSS: -

li 
    { 
        position: relative; 
        margin-left: -15px;
        list-style: none;
    }