本文实例讲述了smarty实现多级分类的方法。分享给大家供大家参考。具体分析如下:
这里简单的介绍一下利用php smarty 多级分类读出与循环方法,单循环很简单,但是多级就要复杂一点,下面我们来看看,感兴趣的朋友可以看来一下:
复制代码 代码如下:
<?php
$result=mysql_query("SELECT id,description,parent_id,name,sort_order FROM article_categoey WHERE parent_id=0 order by id");
while ($row = mysql_fetch_array($result)){
$class[]=$row;
//$row['id']是分类id,parent_id是子分类所属id
$result_sub=mysql_query("SELECT id,description,parent_id,name,sort_order FROM article_categoey WHERE parent_id='".$row['id']."' order by id");
while ($row_sub = mysql_fetch_array($result_sub)) {
$subclass[]=$row_sub;
}
$smarty->assign("subclass", $subclass);
}
$smarty->assign("class", $class);
$smarty->display('articles.html');
?>
$result=mysql_query("SELECT id,description,parent_id,name,sort_order FROM article_categoey WHERE parent_id=0 order by id");
while ($row = mysql_fetch_array($result)){
$class[]=$row;
//$row['id']是分类id,parent_id是子分类所属id
$result_sub=mysql_query("SELECT id,description,parent_id,name,sort_order FROM article_categoey WHERE parent_id='".$row['id']."' order by id");
while ($row_sub = mysql_fetch_array($result_sub)) {
$subclass[]=$row_sub;
}
$smarty->assign("subclass", $subclass);
}
$smarty->assign("class", $class);
$smarty->display('articles.html');
?>
HTML 代码如下:
复制代码 代码如下:
<ul>
{foreach name=cat from=$class item=cat}
<li><strong>{$cat.name}</strong>[{$cat.id}]</li>
<ul style="padding-left:20px;">
{foreach name=subcat from=$subclass item=subcat}
{if $subcat.parent_id==$cat.id}
<li>{$subcat.name}[{$subcat.parent_id}]</li>
{/if}
{/foreach}
</ul>
{/foreach}
</ul>
{foreach name=cat from=$class item=cat}
<li><strong>{$cat.name}</strong>[{$cat.id}]</li>
<ul style="padding-left:20px;">
{foreach name=subcat from=$subclass item=subcat}
{if $subcat.parent_id==$cat.id}
<li>{$subcat.name}[{$subcat.parent_id}]</li>
{/if}
{/foreach}
</ul>
{/foreach}
</ul>
运行结果如下图所示:
希望本文所述对大家的PHP程序设计有所帮助。