我正在尝试设计一个动态的垂直菜单:我的表格是:
primary // primary key
pid //parent id 0 if none
cid //the actual category id
comment //some comment
问题是,我想设计一个php函数,在从数据库中读取值后,它应该将其输出到一个html有序列表(就像一个多级嵌套的无序列表),我知道使用递归函数可以很容易地实现它,但问题是我就是做不到。我已经尝试了很多次,但都失败了,主要的问题是嵌套(在哪里提供列表项目,从哪里开始列表)
如果你们有人能帮我的话我会很感激的.
好吧,我已经设法写了一个丑陋的代码:{这里我使用了两个表,一个用于父表,一个用于子表}
$query="SELECT * FROM parentCat";
$result=mysql_query($query);
echo "<ul id=\"suckertree1\">";
while($row=mysql_fetch_array($result))
{
$name=$row['comment'];
$pid=$row['catid'];
echo "<li><a href=\"#\"> $name</a> ";
$query="select * from childCat WHERE pid=$pid";
$subresult=mysql_query($query);
$af=mysql_num_rows($subresult);
if($af>0)
{
echo "<ul>";
while($subrow=mysql_fetch_array($subresult))
{
$name=$subrow['comment'];
echo "<li><a href=\"#\"> $name</a> </li>";
}
echo "</ul>";
}
echo "</li>";
}
echo "</ul>";
它将只显示一个子层...我该怎么做才能让它在无限级别下工作呢?
发布于 2011-02-12 10:39:00
我觉得一段时间的脚本最适合你
$query = mysql_query("SELECT * FROM menu ORDER BY primary ASC");
$parent=0;
$sub=0
echo "<ul>";//start list
while($menu = mysql_fetch_array($query){
if($parent != $menu['pid']){//if not seen item before
if($sub != 0){echo "</ul>";}else{$sub++;}//if not first submenu, close submenu before. If first sub sub++.
echo "<ul>";}//open submenu
echo "<li>".$menu[cid]."</li>";//echo item
if($parent != $menu['pid']){//if not seen before
$parent = $menu['pid']; //set to seen before so next loop will be recognised
}
}
echo "</ul>"; //end list
我不知道这是否会工作,因为我没有测试它,但它应该会向你展示一个如何做的选项。列表的概念:
<ul>
<li>Item1</li>
<ul>
<li>Subitem1</li>
<li>Subitem2</li>
</ul>
<li>Item 2</li>
<ul>
<li>Subitem1 of Item2</li>
</ul>
</ul>
提供:
Item2的
发布于 2011-02-12 11:10:59
试试这个,应该能行得通。
<?php
$query = "SELECT a.comment parent
, b.comment child
FROM menu a
JOIN menu b
ON a.primary = b.pid
ORDER BY a.primary";
$result = mysql_query($query);
$parent = '';
echo "<ul>";
foreach ($result as $next) {
if ($next['parent'] != $parent) {
if (strlen($parent) > 0) {
echo " </ul>";
echo " </li>";
}
echo " <li>" . $next['parent'];
echo " <ul>";
}
echo " <li>" . $next['child'] . "</li>";
$parent = $next['parent'];
}
echo " </ul>";
echo " </li>";
echo "</ul>";
?>
发布于 2011-02-12 11:22:28
要呈现assoc数组的嵌套列表,请尝试执行以下操作:
<?php
$list = array(
'item-1' => 'test-1',
'item-2' => 'test-2',
'item-3' => array(
'item-3-1' => 'test-3',
'item-3-2' => array(
'item-3-2-1' => 'test-4',
'item-3-2-2' => 'test-5',
),
),
'item-4' => 'test-6',
);
function render_list($list) {
echo '<ul>';
foreach ($list as $key => $value) {
echo '<li>';
echo $key.':';
if (is_array($value)) render_list($value);
else echo $value;
echo '</li>';
}
echo '</ul>';
}
render_list($list);
这将导致以下结果:
<ul>
<li>item-1:test-1</li>
<li>item-2:test-2</li>
<li>
item-3:
<ul>
<li>item-3-1:test-3</li>
<li>
item-3-2:
<ul>
<li>item-3-2-1:test-4</li>
<li>item-3-2-2:test-5</li>
</ul>
</li>
</ul>
</li>
<li>item-4:test-6</li>
</ul>
https://stackoverflow.com/questions/4977399
复制相似问题