【问题标题】:Printing a subarray in an array in smarty (foreach)在 smarty (foreach) 中的数组中打印子数组
【发布时间】:2011-05-29 18:09:17
【问题描述】:

我正在尝试使用 smarty 模板引擎在数组中打印一个子数组。假设我有一个这样的数组结构:

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 中有另一种推荐的方法?任何反馈将不胜感激。谢谢!

【问题讨论】:

    标签: foreach smarty nested-loops multidimensional-array


    【解决方案1】:

    只需添加另一个 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}
    

    【讨论】:

    • 谢谢!我想这很简单。我不知道您可以使用 smarty 访问子数组。使用 smarty 虽然您必须更改上面的其中一行,但它的“文件:{foreach $sourceInfo.fileList as $file}{$file}
      {foreachelse}no files{/foreach }"
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多