Smarty嵌套的foreach循环问题

时间:2010-08-23 23:26:50

标签: php 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] =&gt;排列         (             [title] =&gt;妇女             [id] =&gt; 71             [productCount] =&gt; 3             [171] =&gt;排列                 (                     [id] =&gt; 171                     [title] =&gt;鞋                     [productCount] =&gt; 2                     [74] =&gt;排列                         (                             [id] =&gt; 74                             [title] =&gt;靴子                             [productCount] =&gt; 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
                    )

            )

    )

1 个答案:

答案 0 :(得分:0)

当您在第二个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。