【问题标题】:Smarty loop over nested arraySmarty 循环遍历嵌套数组
【发布时间】:2012-03-19 12:18:23
【问题描述】:

您好,我想打印嵌套数组的数据,这是我的数组:$result[]

结果数组是这样构建的

foreach($pictureIds as $pressId) {
    $picture = PressPicture::_getItemByPressId($pressId);
    $result['picture'][] = $picture;
    $pressItem = PressItem::_fromNumber($pressId);

    if($pressItem) {
        $result['title'][] = $pressItem->getTitle();
    }
}

Array
    (
    [picture] => Array
        (
            [0] => PressPicture Object
                (
                    [id] => 21
                    [data] => Array
                        (
                            [id] => 21
                            [press_id] => 3
                            [update_time] => 1331738139
                            [ord] => 1
                        )

                    [dataLang] => 
                    [prettyClassName] => 
                )

            [1] => PressPicture Object
                (
                    [id] => 31
                    [data] => Array
                        (
                            [id] => 31
                            [press_id] => 4
                            [update_time] => 1332144196
                            [ord] => 1
                        )

                    [dataLang] => 
                    [prettyClassName] => 
                )

        )

    [title] => Array
        (
            [0] => Tetsij
            [1] => Persbericht
        )
)

如何循环这个数组。所以我有我的标题,然后是我的图片。我试过这个

{foreach name=outer item=it from=$result}
<li>
    {foreach from=$it item=value key=key}
      {assign var=item value=$value}
      <img src="{$item->getPictureUrl('list', 180, 120, true, false, true)}" alt="{$item->getTitle()}" width="180" height="120" />
     {/foreach}
</li>
{/foreach}

我可以使用该对象,但如何打印同样在数组中的标题?

【问题讨论】:

  • 你当前的输出怎么样?
  • 我当前的输出给了我一张图片,因为我可以到达图片对象。但我想要的是我的图片 + 我的 $result[] 数组中的标题。
  • 您是否提到将 title 属性添加到您的 PressPicture-Class 中?似乎每张图片都可以有一个标题,因此将标题存储在对象中是一种更简洁的方式。结果,您没有 2 个带有数据要循环的数组,您只有一个,您可以通过 get-Method 访问标题。

标签: php foreach smarty


【解决方案1】:

使用图片 foreach 中的 key 参数作为索引来访问标题数组。

{foreach name=outer item=pictures from=$result.picture}
<li>
    {foreach from=$pictures item=pic key=key}
        <img src="{$pic->getPictureUrl('list', 180, 120, true, false, true)}" alt="{$result.title[$key]}" width="180" height="120" />
    {/foreach}
</li>
{/foreach}

【讨论】:

  • 感谢您的回复,当以这种方式编写 foreach 时:出现错误:致命错误:在非对象中调用成员函数 getPictureUrl()。
  • 我不知道你的 PressPicture 对象实现了哪些方法:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多