php 使用来自 Twig 的数组键访问数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8058994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:52:31  来源:igfitidea点击:

Accessing array values using array key from Twig

phptwig

提问by Joseph Woodward

Does anyone know how (of if it's even possible!) to do this in Twig? I can't see anything in the documentation as to whether it's possible.

有谁知道如何(甚至可能!)在 Twig 中做到这一点?我在文档中看不到任何关于它是否可能的内容。

The PHP array is structured as below:

PHP 数组的结构如下:

$data['data']['a']['title'] = 'Title 1';
$data['data']['a']['title'] = 'Title 2';
$data['data']['b']['title'] = 'Title 3';

Twig template code below:

Twig模板代码如下:

{% for letter in 'a'..'z' %}
    {{ letter }}
    <ul>
        {% for key, item1 in data %}
            {% for item2 in item1 %}

                <li>{{ item2[key].title }}</li>

            {% endfor %}
        {% endfor %}                
    </ul>
{% endfor %}

Edit:After further investigation, it appears the attribute (see http://twig.sensiolabs.org/doc/functions/attribute.html) function should do the job but I am unsure as to how to use it in these circumstances.

编辑:经过进一步调查,似乎属性(参见http://twig.sensiolabs.org/doc/functions/attribute.html)函数应该可以完成这项工作,但我不确定如何在这些情况下使用它。

Many thanks

非常感谢

回答by Guillaume Poussel

Have you just tried this:

你有没有试过这个:

attribute(item2, key).title