我的 mysql 表如下所示:
我需要制作 3 级树,没有 House_NR。
-Country
|--City 1
| |--Street 1
| |--Street 2
|
|--City 2
|--City 3
| |--Sreet 1
| |--Steet 2
在 PHP 中,我进行了这个 sql 查询:
SELECT
l.Country_ID,
c1.Name AS Country_Name,
l.City_ID,
c2.Name AS City_Name,
l.Street_ID,
s.Name AS Street_Name,
l.House_NR
FROM Location l
JOIN Country c1 ON c1.id = l.Country_ID
JOIN City c2 ON c2.id = l.City_ID
JOIN Street s ON s.id = l.Street_ID
我有这个功能:
function getTree($data) {
$tree = prepareTree($data);
drawTree($tree);
}
function prepareTree($data) {
$nodeList = array();
$tree = array();
foreach ($data as $key) {
$tree[$key["Country_ID"]]["name"] = $key["Country_Name"];
$tree[$key["Country_ID"]]["id"] = $key["Country_ID"];
$tree[$key["Country_ID"]]["level"] = 1;
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["name"] = $key["City_Name"];
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["id"] = $key["City_ID"];
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["level"] = 2;
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["children"][$key["Street_ID"]]["name"] = $key["Street_Name"];
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["children"][$key["Street_ID"]]["id"] = $key["Street_ID"];
$tree[$key["Country_ID"]]["children"][$key["City_ID"]]["children"][$key["Street_ID"]]["level"] = 3;
}
return $tree;
}
function drawTree($data, $sub = false) {
echo ($sub) ? "<ul class=\"tree-listCat\">" : "<ul class=\"tree-list\">";
foreach($data as $key) {
if ($key["children"] != null) {
echo "<li class=\"tree-itemCat\"><span class=\"tree-itemSel\"><a href=\"switch.php?action=search&type=tree&level=" . $key["level"] . "&id=" . $key["id"] . "\">" . $key["name"] . "</a></span></li>";
drawTree($key["children"], true);
} else
echo "<li class=\"tree-item\"><span class=\"tree-itemSel\"><a href=\"switch.php?action=search&type=tree&level=" . $key["level"] . "&id=" . $key["id"] . "\">" . $key["name"] . "</a></span></li>";
}
echo "</ul>";
}
这个函数工作正常,但是函数中存在一些问题,现在函数绘制一个 html 版本的树我有这个:
action=search&type=tree&level=" . $key["level"] . "&id=" . $key["id"]
,但我需要有这样的东西:
如果只有没有孩子的国家,那么action=search&type=tree&country=id
如果只有没有孩子的国家和城市街道,那么action=search&type=tree&country=id&city=id
如果所有参数国家、城市和街道,那么action=search&type=tree&country=id&city=id&street_id=id
而且功能准备树看起来很糟糕(在我看来)。简而言之,我需要从Location
数据库中创建一棵树。