[英]how to draw a tree structure in php from mysql data?
我有下面的mysql記錄,所以需要使用下面的mysql數據在php中繪制一個樹結構,這里NULL
值代表主要的父節點,
+----------------+----------------+
| child | parent |
+----------------+----------------+
| 216 | 103 |
| 217 | 216 |
| 88 | 216 |
| 102 | NULL |
| 103 | 102 |
| 104 | 102 |
+----------------+----------------+
輸出應該是以下格式
102
/ \
103 104
/
216
/ \
217 218
請幫我
為父子創建數組的函數:
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));
?>
輸出:
可以使用的小型 CSS :-
li
{
position: relative;
margin-left: -15px;
list-style: none;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.