我的桌子看起来像
ID | Parent | Name | Level
1 | 0 | Cat1 | 0
2 | 1 | SubCat1 | 1
3 | 0 | Cat2 | 0
4 | 3 | SubCat2 | 1
5 | 4 | SubCat3 | 2
6 | 3 | SubCat4 | 3
我需要按顺序显示数据:
Cat1
SubCat1
Cat2
Subcat2
SubCat3
SubCat4
我可以用递归函数很好地执行它,但现在的要求是不用递归函数。请帮忙,我也对级别字段感到困惑。
从数据库中获取的代码:
class Sitemap
{
public static function getTopCategories()
{
return self::getCategories('parent=0');
}
public static function getCategories($where='')
{
if ($where) $where = " WHERE $where";
$result = mysql_query("SELECT * FROM sitemap $where");
$categories = array();
//while ($category = mysql_fetch_object($result, 'Category'))
while ($category = mysql_fetch_array($result)){
$my_id = $category['id'];
$category['children'] = Sitemap::getCategories("parent = $my_id");
$categories[] = $category;
}
mysql_free_result($result);
return $categories;
}
}
要显示的代码(使用 Smarty):
{foreach from=$sitemap item=c name=sitemap}
{if $c.parent ==0 }
<li><h2><a title="{$c.name}" href="{$c.url}">{$c.name}</a></h2><ul>
{foreach item=d from=$c.children name=sitemap}
<li><a title="{$d.name}" href="{$d.url}">{$d.name}</a></li>
{/foreach}
{else}
<li><h2><a title="{$c.name}" href="{$c.url}">{$c.name}</a></h2><ul>
{/if}
</ul>
</li>
{/foreach}