【问题标题】:Smarty Nested foreach loop questionSmarty 嵌套 foreach 循环问题
【发布时间】:2010-08-23 23:26:49
【问题描述】:

我无法在 smarty 模板文件中正确显示以下数组。如果有人能帮助我指出正确的方向,我将不胜感激。

我的模板代码如下所示:

          {foreach from=$trackingGroups item=gender key=k item=v}
          {assign var=tc value="`$v.id`"}    
          {$v.title} ({$v.productCount})<br />

{foreach item=department from=$trackingGroups.$tc item=v2} {$v2.title}
{/foreach} {/foreach}

但页面显示如下:

          Women (3)<br />
           W<br />
                    7<br />
                    3<br />
                    Footwear<br />
                    Accessories<br />

          Men (2)<br />
           M<br />
                    7<br />
                    2<br />
                    Footwear<br />




Array

( [71] => 数组 ( [标题] => 女性 [编号] => 71 [产品数量] => 3 [171] => 数组 ( [id] => 171 [标题] => 鞋类 [产品数量] => 2 [74] => 数组 ( [id] => 74 [标题] => 靴子 [产品数量] => 2 )

            )

        [172] => Array
            (
                [id] => 172
                [title] => Accessories
                [productCount] => 1
                [74] => Array
                    (
                        [id] => 74
                        [title] => Boots
                        [productCount] => 1
                    )

            )

    )

[72] => Array
    (
        [title] => Men
        [id] => 72
        [productCount] => 2
        [171] => Array
            (
                [id] => 171
                [title] => Footwear
                [productCount] => 2
                [74] => Array
                    (
                        [id] => 74
                        [title] => Boots
                        [productCount] => 2
                    )

            )

    )

)

【问题讨论】:

  • 你能正确标记你的第一个代码块吗?目前很难跟上。

标签: php smarty


【解决方案1】:

当您在第二个 foreach 中循环时,您将遍历所有元素,而不仅仅是 title 键。例如:

{foreach item=department from=$trackingGroups.72 item=v2} 
   {$v2.title}
{/foreach}

在这种情况下,$v2 将采用以下值:

[title] => Men
[id] => 72 
[productCount] => 2 
[171] => Array 
 ( 
                [id] => 171 
                [title] => Footwear 
                [productCount] => 2 
                [74] => Array 
                    ( 
                        [id] => 74 
                        [title] => Boots 
                        [productCount] => 2 
                    ) 

 ) 

第一个、第二个和第三个值将只是一个字符串。由于不是数组,$v2.title 会返回第“title”的元素(第一个),返回第一个字符:M,7,2 第四个元素是一个带有“title”键的数组,正确返回:Footwear。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多