2011-10-13 81 views
1

我需要显示查询的结果(mysql),我怎样才能循环记录集,而不需要将值赋给数组? 现在我做:如何使用Smarty打印记录集?

while($row = $this->mysql->fetch($rs)){ 
    val[] = $row 
} 
$this->smarty->assign('val', val); 

然后(在template.tpl)

{section name=nr loop=$val} 
{$val[nr].cod}<br /> 
{sectionelse} 
<h1>No record</h1> 
{/section} 

我如何优化呢?

回答

1

您可以使用Smarty的的foreach,虽然它并不能使它更短:

{if $val} 
    {foreach from=$val item=nr} 
     {$nr.cod}<br /> 
    {/foreach} 
{else} 
    <h1>No record</h1> 
{/if} 
+0

不,我问如何显示“记录集”(我的记录集),你可以看到我将行保存在一个数组中,我需要这样做吗?我能否直接打印记录集? – Dail

+0

@Dail除非在Smarty模板中嵌入PHP代码,否则不能将其保存到数组中而不打印记录集。这是不受欢迎的做法。首先将它存储到数组是处理它的正确方法。 –

+0

@Michael,这不慢吗? – Dail

0

也许{html_table}可以提供帮助。否则,你可以自由地重复你的行列数,只要你喜欢:

{foreach $val as $row} 
    {if [email protected]} 
    <table> 
    <tbody> 
    {/if} 
    {foreach $row as $cell} 
     {if [email protected]} 
     <tr> 
     {/if} 

     <td>{$cell|escape:"html}</td> 

     {if [email protected]} 
     </tr> 
     {/if} 
    {foreach} 
    {if [email protected]} 
    </tbody> 
    </table> 
    {/if} 
{foreachelse} 
    <p>No Data</p> 
{/foreach} 

(的{foreach} Smarty3语法)

您也可以输出细胞键:

{foreach $val as $row} 
    {if [email protected]} 
    <table> 
    <thead> 
    <tr> 
    {foreach $row as $cell} 
     <th>{[email protected]|escape:"html}</th> 
    {/foreach} 
    </tr> 
    </thead> 
    <tbody> 
    {/if} 
    {foreach $row as $cell} 
     {if [email protected]} 
     <tr> 
     {/if} 

     <td>{$cell|escape:"html}</td> 

     {if [email protected]} 
     </tr> 
     {/if} 
    {foreach} 
    {if [email protected]} 
    </tbody> 
    </table> 
    {/if} 
{foreachelse} 
    <p>No Data</p> 
{/foreach}