dongqiao0953 2016-07-20 22:42
浏览 75
已采纳

Twig中的多维数组

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条回答 默认 最新

  • doulu1867 2016-07-20 22:50
    关注

    Try this:

    {% for type, items in data %}
        {{ type }}
    
        {% for key, value in items %}
            - {{ key }}
                - {{ value.name }}, {{ value.quantity }}, {{ value.price }}
        {% endfor %}
    {% endfor %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 关于#tensorflow#的问题:有没有什么方法可以让机器自己学会像素风格的图片
    • ¥15 Oracle触发器字段变化时插入指定值
    • ¥15 docker无法进入容器内部
    • ¥15 qt https 依赖openssl 静态库
    • ¥15 python flask 报错
    • ¥15 改个密码引发的项目启动问题
    • ¥100 CentOS7单线多拨
    • ¥15 debian安装过程中老是出现无法将g21dr复制到g21dr怎么解决呀?
    • ¥15 如何用python实现跨工作簿的指定区域批量复制粘贴
    • ¥15 基于CH573f的雷迪安CR1400m通讯代码