沃梦达 / 编程问答 / php问题 / 正文

Twig 中的多维数组

Multidimensional Array in Twig(Twig 中的多维数组)

本文介绍了Twig 中的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Twig 与 PHP 一起使用.我有一个这样的多维数组设置:

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?

推荐答案

试试这个:

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

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

这篇关于Twig 中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Twig 中的多维数组

基础教程推荐