我的数据库中有两个表:
table name: Table1 Table2
columns id1;name1 id2;name2;id1
我想使用PHP输出项目的嵌套列表:
<ul>
<li>item1 (from t1)</li>
<li>item2 (from t1)</li>
<li>item3 (from t1)
<ul>
<li>item1 (from t2 where id1 -> item3)</li>
<li>item2 (from t2 where id1 -> item3)</li>
</ul>
</li>
<li>item4 (from t1)</li>
...
</ul>
我想在服务器端进行此操作,但也欢迎使用CSS的任何建议。非常感谢您的宝贵时间。
汤姆
好吧,我现在明白了:
查询是:
SELECT name1,name2
FROM Table1 left join Table2 on Table1.id1=Table2.id1
ORDER by Table1.id
表2中的id1是外键= Table1.id1
然后是此PHP代码生成html列表:
echo "<ul>";
$a =""; // helpers
$b = 0;
while($row = mysqli_fetch_array($result)) {
if (isset($row['name2']) and $row['name1'] != $a and $b == 0) {
echo "<li>".$row['name1']."<ul>";
echo "<li>".$row['name2']."</li>";
$a = $row['name1'];
$b = 1;
}
elseif (isset($row['name2']) and $row['name1'] == $a and $b == 1) {
echo "<li>".$row['name2']."</li>";
}
elseif (isset($row['name2']) and $row['name1'] != $a and $b == 1) {
echo "</ul>";
echo "<li>".$row['name1']."<ul>";
echo "<li>".$row['name2']."</li>";
$a = $row['name1'];
$b = 1;
}
elseif (!isset($row['name2']) and $row['name1'] !=$a and $b == 1) {
echo "</ul>";
echo "<li>".$row['name1']."</li>";
$a = $row['name1'];
$b = 0;
}
else {
echo "<li>".$row['name1']."</li>";
$a = $row['name1'];
$b = 0;
}
}
echo "</ul>";
只是要补充一点,没有名称1就不能有name2,而名称1不能有name2。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句