Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a multidimensional Twig array for values?

Tags:

arrays

twig

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',
        ),
    ),
);

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.

like image 626
Peter Avatar asked Feb 23 '15 10:02

Peter


People also ask

How do you access multidimensional arrays?

Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP. Elements can be accessed using dimensions as array_name['first dimension']['second dimension']. Elements can be accessed using for loop. Elements can be accessed using for each loop.

Is a multidimensional array an array of arrays?

A multidimensional array is an array containing one or more arrays.


2 Answers

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 }}
like image 186
oshell Avatar answered Oct 05 '22 23:10

oshell


this one is more like a multidimensional loop in case it's necessary

   {% for animals in array %}

        {% set dogs = animals.dogs %}

        {% for dog in dogs %}
            {{ dump(dog.type) }}
        {% endfor%}

    {% endfor %}
like image 39
joe Avatar answered Oct 05 '22 23:10

joe