Multidimensional Array in Twig

走远了吗. 提交于 2020-12-01 12:10:37

问题


I am using Twig with PHP. I have a multidimensional array setup like this:

Array
(
[Special] => Array
    (
        [277] => Array
            (
                [name] => First Item
                [quantity] => 1
                [price] => 0
            )

        [276] => Array
            (
                [name] => Second Item
                [quantity] => 11
                [price] => 0
            )

        [278] => Array
            (
                [name] => Third Item
                [quantity] => 2
                [price] => 0
            )

    )

[Technical] => Array
    (
        [14] => Array
            (
                [name] => First Item
                [quantity] => 1
                [price] => 1
            )
    )
[Books] => Array
    (
        [169] => Array
            (
                [name] => First Item
                [quantity] => 2
                [price] => 100
            )

        [361] => Array
            (
                [name] => Second Item
                [quantity] => 1
                [price] => 2
            )
    )
)

I need to be able to cycle through each of the keys in the first array(Special, Technical, Books) and print these as category headers. I have been able to do that using:

{% for type, items in data %}
{{ type }}
{% endfor %}

This part is working fine. What I am having trouble with, is how do I loop through the items in each category and print those? The output should be like this:

Special
    - 277
        - {name}, {quantity}, {price}
    - 276
        - {name}, {quantity}, {price}
Technical
    - 14
        - {name}, {quantity}, {price}
...

How can I go about outputting the data like this?


回答1:


Try this:

{% for type, items in data %}
    {{ type }}

    {% for key, value in items %}
        - {{ key }}
            - {{ value.name }}, {{ value.quantity }}, {{ value.price }}
    {% endfor %}
{% endfor %}


来源:https://stackoverflow.com/questions/38492062/multidimensional-array-in-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!