如何检查多维 Twig 数组的值?多维、数组、Twig

2023-09-06 23:56:50 作者:☆⌒糖果罐子℡

要简单地检查一个数组是否包含某个值,我会这样做:

To simply check if an array contains a certain value I would do:

{% if myVar in someOtherArray|keys %}
...
{% endif %}

但是,我的数组是多维的.

However, my array is multi-dimensional.

$tasks = array(
    'someKey' => 'someValue',
    ...
    'tags' => array(
        '0' => array(
            'id'   => '20',
            'name' => 'someTag',
        ),
        '1' => array(
            'id'   => '30',
            'name' => 'someOtherTag',
        ),
    ),
);

我希望能够检查 $tasks['tags'] 的标签 id 是否为 20.我希望我不会因为使用 PHP 数组格式而让您感到困惑.

What i would like is to be able to check if the $tasks['tags'] has tag id 20. I hope I'm not confusing you by using the PHP array format.

推荐答案

设置标志并使用循环.之后,您可以在 if 条件中使用该标志.

Set a flag and use a loop. Afterwards you can use the flag in if conditions.

{% set flag = 0 %}
{% for tag in tasks.tags %}
    {% if tag.id == "20" %}
        {% set flag = 1 %}
    {% endif %}
{% endfor %}
{{ flag }}