我有一个递归函数来显示类别和子类别,它工作正常,但每个地方都添加了额外的<ul></ul>
。
php code
<?php
echo '<ul class="nav">';
function mainMenu($parentId, $connection) {
$sqlTours = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ORDER BY category_order ASC";
$rsTours = mysql_query($sqlTours, $connection) or die(mysql_error());
$totalToursRows = mysql_num_rows($rsTours);
echo "<ul>";
while($rowsTours = mysql_fetch_assoc($rsTours)) {
$categoryId = $rowsTours['category_id'];
$categoryName = $rowsTours['category_name_en'];
echo "<li>"
<a href=\"products.php?category_id=".$categoryId ."\"
data=\"".$categoryId."\">".$categoryName."</a>";
mainMenu($categoryId, $connection);
echo "</li>";
}
echo "</ul>";
}
mainMenu(0, $connection);
echo '</ul>';
?>
这是我从这个功能获得的HTML
<ul class="nav">
<ul>
<li> <a href="products.php?category_id=1" data="1">Egypt</a>
<ul>
<li> <a href="products.php?category_id=2" data="2">Hurghada</a>
<ul>
<li> <a href="products.php?category_id=7" data="7">Sea Trips</a>
<ul>
</ul>
</li>
<li> <a href="products.php?category_id=6" data="6">Safari Trips</a>
<ul>
</ul>
</li>
</ul>
</li>
<li> <a href="products.php?category_id=3" data="3">Sharm El Sheikh</a>
<ul>
</ul>
</li>
<li> <a href="products.php?category_id=4" data="4">Taba</a>
<ul>
</ul>
</li>
</ul>
</li>
<li> <a href="products.php?category_id=5" data="5">Turkey</a>
<ul>
</ul>
</li>
</ul>
</ul>
这是预期的输出
<ul class="nav">
<li><a href="products.php?category_id=1" data="1">Egypt</a>
<ul>
<li><a href="products.php?category_id=2" data="2">Hurghada</a>
<ul>
<li><a href="products.php?category_id=7" data="7">Sea Trips</a></li>
<li><a href="products.php?category_id=6" data="6">Safari Trips</a></li>
</ul>
</li>
<li><a href="products.php?category_id=3" data="3">Sharm El Sheikh</a></li>
<li><a href="products.php?category_id=4" data="4">Taba</a></li>
</ul>
</li>
<li> <a href="products.php?category_id=5" data="5">Turkey</a></li>
</ul>
答案 0 :(得分:1)
如果我理解你的问题,你想要摆脱递归下降底部的空<ul></ul>
标签。
您已将行计入$totalToursRows
,因此请使用它来阻止创建空节点:
function mainMenu($parentId, $connection) {
$sqlTours = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ORDER BY category_order ASC";
$rsTours = mysql_query($sqlTours, $connection) or die(mysql_error());
$totalToursRows = mysql_num_rows($rsTours);
if ($totalToursRows > 0) {
if ($parentId !== 0) {
echo "<ul>";
}
while($rowsTours = mysql_fetch_assoc($rsTours)) {
$categoryId = $rowsTours['category_id'];
$categoryName = $rowsTours['category_name_en'];
echo "<li>";
echo "<a href=\"products.php?category_id=".$categoryId ."\"
data=\"".$categoryId."\">".$categoryName."</a>";
mainMenu($categoryId, $connection);
echo "</li>";
}
if ($parentId !== 0) {
echo "</ul>";
}
}
}
mainMenu(0, $connection);
根据评论请求编辑。