Twig循环遍历数组

时间:2016-10-18 14:57:21

标签: html symfony twig

我有以下json_decode数据,如下所示:

Array 
( 
[0] => Array ( 
    [id] => 218 
    [startTime] => 1478363400000 
    [EndTime] => 1478367000000 
    [c] => Array ( 
        [id] => 1 
        [code] => A 
        [name] => Name 
        [postalCode] => 7TF 
        [contact] => 1111 242 3144 
        [email] => 
        [website] => / 
        [fax] => 
        [address] => Thisistheaddress 
        [latitude] => 53.80729675111 
        [longitude] => -1.5190633535385 
        [status] => ONLINE
    )
    [service] => Array ( 
        [id] => 1 
        [code] => 100 
        [description] => GENERAL 
    )
) 
[1] => Array ( [id] => 237 [startTime] => 1478593800000 [EndTime] => 1478597400000 [c] => Array ( [id] => 1 [code] => A [name] => Name [postalCode] => 7TF [contact] => 1111 242 3144 [email] => [website] => / [fax] => [address] => Thisistheaddress [latitude] => 53.80729675111 [longitude] => -1.5190633535385 [status] => ONLINE ) [service] => Array ( [id] => 1 [code] => 100 [description] => GENERAL ) ) 
[2] => Array ( [id] => 199 [StartTime] => 1478187000000 [EndTime] => 1478190600000 [c] => Array ( [id] => 1 [code] => A [name] => Name [postalCode] => 7TF [contact] => 1111 242 3144 [email] => [website] => / [fax] => [address] => Thisistheaddress [latitude] => 53.80729675111 [longitude] => -1.5190633535385 [status] => ONLINE ) [service] => Array ( [id] => 1 [code] => 100 [description] => GENERAL ) ) 
) 

我的问题是我如何迭代这样我才能在树枝上得到[startTime],[name]和[address]。我尝试过以下方法:

 {% for key,a in TimeInfo|keys %}
    Key : {{ key }}
 {% endfor %}

上面的结果只是给了我一把钥匙,我也尝试了以下内容:

 {% for a in TimeInfo %}
   {{ a.name }}
 {% endfor %}

以上结果是错误的。感谢帮助:)

2 个答案:

答案 0 :(得分:0)

在将TimeInfo数组传递给twig模板之前,请确保使用json_decode函数。您可以将其作为简单的多维数组进行迭代。使用startTime / StartTime的小技巧将帮助您避免与数据数组的StartTime元素键中的第一个大写字母相关的错误。

<ul>
    {% for array in TimeInfo %}
        <li>
            <ul>
                <li>Start Time: {{ attribute(array, 'startTime') ?: attribute(array, 'StartTime') }}</li>
                <li>Name: {{ attribute(array, 'c').name }}</li>
                <li>Address: {{ attribute(array, 'c').address }}</li>    
            </ul>
       </li>
    {% endfor %}
</ul>

答案 1 :(得分:0)

您的第二次循环尝试已关闭但初始数组键上不存在name键。 id, startTime, EndTime, c, servicename密钥似乎嵌套在c下。所以你应该可以像访问它一样访问它:

{% for a in TimeInfo %}
    The start time is: {{ a.startTime }}
    The Name is: {{ a.c.name }} {# notice we access "c" then "name" #}
{% endfor %}