$query = “SELECT id,name,name_cn FROM di_flag ORDER BY id desc”; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $query2=”SELECT id, name, name_cn,flag FROM di_sort WHERE di_sort.flag =$row[id] ORDER BY id desc”; $result2=mysql_query($query2); while($row2 = mysql_fetch_array($result2)) { $post[]=array(’sid’=>$row2[’id’], ’sortname’=>$row2[’name’], ); } $row_array[] = array(’cid’=>$row[’id’], ‘cat_name’=>$row[’name’], ‘topic’=>$post ); unset($post); } $smarty->assign(”forum”,$row_array); unset($row_array); 很简单,以上是一个二维数组,然后再看如何嵌套循环,这回用foreach咯,看代码: {foreach from=$forum ietm=value} <div class=”sort_list”> <a href=”products.php?flag={$value.cid}” mce_href=”products.php?flag={$value.cid}” title=”{$value.cat_name}”>{$value.cat_name}</a> {foreach from=$value.topic ietm=value2} <div class=”sort_list02″><a href=”products.php?sort={$value2.sid}” mce_href=”products.php?sort={$value2.sid}” title=”{$value2.sortname}”>{$value2.sortname}</a></div> {/foreach} </div> {/foreach} 然后用section: test.php <?php require_once('./include/db_fns.php'); include_once("./Smarty/libs/Smarty.class.php"); //包含Smarty类文件 $smarty = new Smarty(); //建立Smarty实例对象$Smarty $smarty->template_dir = "./templates/dedecms";//设置模板目录 $smarty->compile_dir = "templates/templates_c"; //设置编译目录 $smarty->assign("template_url", "./"); $smarty->assign("$site_url", "http://www.gotop.net.ru"); $smarty->assign("$site_name", "文章管理系统"); $smarty->left_delimiter = "<{"; //设置左边界符 $smarty->right_delimiter = "}>"; //设置右边界符 $db_conn = db_connect(); $query = "Select cat_id,cat_name FROM categories orDER BY cat_ID DESC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $query2="Select post_id, post_title, post_date FROM post Where post.post_category =$row[cat_id] AND post_status <> 'unpublish' orDER BY post_date DESC LIMIT 5"; //这里加一个 LIMIT 5 不要用什么$i来控制 $result2=mysql_query($query2); while($row2 = mysql_fetch_array($result2)) { $post[]=array('post_id'=>$row2['post_id'], 'post_title'=>$row2['post_title'], 'post_date'=>date('m-d',strtotime($row2[post_date])) ); } $row_array[] = array('cat_id'=>$row['cat_id'], 'cat_name'=>$row['cat_name'], 'post'=>$post ); unset($post); //$post[]在使用完后要注销,因为使用赋值语句对$post进行赋值时不会 //将它清空,而是将新数组作为它的一个元素增加,为了不产生副作用,这里使用unset()是必需的. //如果不注销,第二次循环的结果会包含第一循环的数据,如分类2的文章跑到分类1中来。 } echo"</br>row_array数组:</br>"; print_r($row_array);//打出来看看有没有数据 $smarty->assign("row_array", $row_array); $smarty->display("test2.htm"); ?> test.htm <?php <html> <head> <title>巢状循环测试</title> </head> <body> <{section name=sec1 loop=$row_array}> <table width="322" border="1" align="center" cellpadding="3" cellspacing="0"> <tr> <td colspan="2"><{$row_array[sec1].cat_id}></td> </tr> <{section name=sec2 loop=$row_array[sec1].post}> <tr> <td width="160">post_title:<{$row_array[sec1].post[sec2].post_title}> </td> <td width="160">post_date:<{$row_array[sec1].post[sec2].post_date}></td> </tr> <{/section}> </table> <{/section}> </body> </html> ?>