2011-05-29 69 views
1

我試圖用smarty模板引擎在數組中打印子數組。說我有這樣的陣列結構:在smarty中打印數組中的子數組(foreach)

Array 
    (
[0] => Array 
    (
     [directory] => One Day As A Lion - 2011-03-01/ 
     [source_notes] => iRiver 
     [recording_type] => Audience 
     [type] => Audio 
     [source_type] => MP3 
     [fileList] => Array 
      (
       [0] => 09 One Day As A Lion.mp3 
       [1] => 01 Intro.mp3 
       [2] => 05 Ocean View.mp3 
       [3] => 04 Swashbuckler.mp3 
       [4] => One Day As A Lion - 2011-03-01 - Prince Bandroom, Melbourne, Australia.jpg 
       [5] => 10 Peart Plus.mp3 
       [6] => 06 Rockers.mp3 
       [7] => 03 Last Letter.mp3 
       [8] => 07 Swampy.mp3 
       [9] => 02 If You Fear Dying.mp3 
       [10] => 08 Wild International.mp3 
      ) 

    ) 

) 

我到底該如何得到含smarty打印文件名的數組?目前我有一個smarty foreach循環,看起來像:

{foreach $sources as $sourceInfo} 
    {strip}  
    Recording Type: {$sourceInfo.type} : {$sourceInfo.recording_type}<br> 
    Source : {$sourceInfo.source_notes}<br>  
    {/strip} 
    {/foreach} 

而且我不知道如何實現第二個foreach循環。有沒有人有什麼建議?我對文檔有點困惑,因爲似乎有兩種嵌套的foreach循環方法,其中一種似乎不推薦使用。是否foreach循環是最好的方式呢,還是在smarty中有另一種推薦的方法?任何反饋將不勝感激。謝謝!

回答

4

只需添加其他的foreach:

{foreach from=$sources item=sourceInfo} 
    {strip}  
    Recording Type: {$sourceInfo.type} : {$sourceInfo.recording_type}<br> 
    Source : {$sourceInfo.source_notes}<br>  
    Files: {foreach from=$sourceInfo.fileList item=file}{$file}, {foreachelse}<i>no files</i>{/foreach} 
    {/strip} 
{/foreach} 
+0

謝謝!我覺得這很簡單。我不知道你可以像smarty那樣訪問子數組。儘管你必須改變上面的一行,所以它的「Files:{foreach $ sourceInfo.fileList as $ file} {$ file}
{foreachelse} 沒有文件 {/ foreach}」< - 基本上你需要括號$文件。 – thomascirca 2011-05-29 18:31:46

+0

啊,是的,錯過了。你當然是對的。 – Czechnology 2011-05-29 18:52:34