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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?