我有一大堆的名字 - parentname对,我想转成少数heirarchical树形结构成为可能.例如,这些可能是配对:
Child : Parent
H : G
F : G
G : D
E : D
A : E
B : C
C : E
D : NULL
Run Code Online (Sandbox Code Playgroud)
需要转化为(a)层次结构树:
D
??? E
? ??? A
? ? ??? B
? ??? C
??? G
??? F
??? H
Run Code Online (Sandbox Code Playgroud)
我想要的最终结果是一组嵌套的<ul>元素,每个元素都<li>包含孩子的名字.
有在配对没有不一致(孩子是它自己的父母,父母是孩子的孩子,等等),所以一堆优化大概可以做.
在PHP中,我如何从包含child => parent对的数组转到一组嵌套<ul>s?
我有一种感觉,涉及到递归,但我还没有完全清醒地思考它.
我试图将我的数据分层设置为树遍历模型到<ul>,以便在我的网站上显示.
这是我的代码:
function getCats($) {
// retrieve all children of $parent
$query = "SELECT max(rght) as max from t_categories";
$row = C_DB::fetchSingleRow($query);
$max = $row["max"];
$result ="<ul>";
$query = "SELECT * from t_categories where lft >=0 and rght <= $max";
if($rs = C_DB::fetchRecordset($query)){
$p_right ="";
$p_left ="";
$p_diff="";
while($row = C_DB::fetchRow($rs)){
$diff = $row["rght"] -$row["lft"];
if($diff == $p_diff){
$result.= "<li>".$row['title']."</li>";
}elseif (($row["rght"] - $row["lft"] > 1) && ($row["rght"] > $p_right)){
$result. "<ul>";
$result.= "<li>".$row['title']."</li>";
}else{
$result.= "<li>".$row['title']."</li>";
}
$p_right = …Run Code Online (Sandbox Code Playgroud) 我在MySQL数据库中有以下数据:
Autonum ID Name MetaValue
1 1 Rose Drinker
2 1 Rose Nice Person
3 1 Rose Runner
4 2 Gary Player
5 2 Gary Funny
Run Code Online (Sandbox Code Playgroud)
我现在正在使用PHP,但是我使用C#,Java和其他语言多次遇到过这个问题.
现在我过去和现在的目标是以下列格式显示数据:
<table>
<thead>
<th>Name</th>
<th>MetaValue1</th>
</thead>
<tbody>
<tr>
<td>Rose</td>
<td>
<ul>
<li>Drinker</li>
<li>Nice Person</li>
<li>Runner</li>
</ul>
</td>
</tr>
<tr>
<td>Gary</td>
<td>
<ul>
<li>Player</li>
<li>Funny</li>
</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
我之前通过创建一个代表我的SQL表的类来解决这个问题.然后我创建了一个Dictionary持有EmployeeId和类.
Dictionary<string,MyTable> MyData = new <string,MyTable>();
Table MyMetaData = new Table();
MyMetaData SomeMetaData=getMetaValueList();//imagine a web service that does that
MyData.add(EmployeeId,SomeMetaData);
Run Code Online (Sandbox Code Playgroud)
我正在跳过步骤,但我希望你明白我的观点.我可能只需要关键字来称呼这类问题.完成此任务的首选方法是什么?