2011-05-18 66 views
0

從我的理解中,Smarty包含了許多與PHP等價的內置函數。如何將此Smarty代碼轉換回PHP?

如何將下面的代碼轉換回原生PHP? 「部分」與for循環相似嗎?

<table width="400" border="0"> 
    {section name=x loop=$records} 
    <tr> 
     {section name=y loop=$records[x]} 
     <td align="right"> 
      <input type="checkbox" name="{$records[x][y].prefkey}" {if $records[x][y].prefval eq "on"}checked{/if} /> 
     </td> 
     <td align="left"> 
      <strong>&nbsp;{$records[x][y].prefkey}</strong> 
     </td> 
     {/section} 
    </tr> 
    {/section} 
</table> 

回答

2

下面是一個例子,使用您的數據對象的簡單數組:

<?php                        
// generate some test data                   
$records = array(                     
    array(                       
     array('prefkey'=>"foo",'prefval'=>"on"),              
     array('prefkey'=>"bar",'prefval'=>"off"),             
    ),                        
    array(                       
     array('prefkey'=>"foo",'prefval'=>"off"),             
     array('prefkey'=>"bar",'prefval'=>"off"),             
    ),                        
    array(                       
     array('prefkey'=>"foo",'prefval'=>"off"),             
     array('prefkey'=>"bar",'prefval'=>"on"),              
    ),                        
);                         
?>                         
<table width="400" border="0">                  
<?php for($x=0; $x<count($records); $x++){ ?>              
<tr>                         
    <?php for($y=0; $y<count($records[$x]); $y++){ ?>            
     <td align="right"> 
     <input type="checkbox" name="<?=$records[$x][$y]['prefkey']; ?>" <?=($re      
cords[$x][$y]['prefval'] == "on"? "checked" : "") ?>/></td>           
     <td align="left">                   
      <strong>&nbsp;<?=$records[$x][$y]['prefkey']; ?></strong>        
     </td>                      
     <?php }?>                     
</tr>                        
<?php }?>                       
</table> 

如果數據包含在實際的對象,您需要更改訪問器語法。

1

{section name=x loop=$records}{section}

相當於foreach(array_keys($records) as $x) { }

+1

根據文檔,{section}適用於順序數組,而不適用於關聯數組。 http://www.smarty.net/docsv2/en/language.function.section.tpl – 2011-05-18 18:18:35

+0

所以這仍然有效? – 2011-05-18 18:22:50

+0

@AJ你說得對。謝謝。根據文檔,@Trenton Scott,這是行不通的 – Damp 2011-05-18 18:56:04