Drudge Rajen
Drudge Rajen

Reputation: 7987

Twig:Check array key value with condition

Mine data after fetching from db is as below:

1,7 or 1 or 2,6 or 3,4

i.e. at any combination from 1 to 7 number. where 1 to 7 reflects the days data that is

7=>sunday
1=>monday
2=>tuesday
----
---
6=>saturday

The vairable is array. So, there is any way of doing this type of array filter so that if data is 1,7 then i can check and get saturday,sunday ? i.e

{% if some condition meets within data array %}
value
{% else %}

Thanks

Upvotes: 1

Views: 1225

Answers (2)

Jason Roman
Jason Roman

Reputation: 8276

Not sure what your question is exactly but you can check if values exist in an array pretty easily:

{% if 1 in data_array %}

{% endif %}

If you're looking for a specific key to exist:

{% if data_array.key is defined %}

{% endif %}

EDIT from your other answer:

You could also try cleaning up the loop a little bit by setting a quick day map in your twig:

{% set dayMap = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'} %}

{% for d in data_array %}
    {% for day in d.days %}
        {{ dayMap[day] }}{% if not loop.last %}, {% endif %}
    {% endfor %}
{% endfor %}

Upvotes: 1

Drudge Rajen
Drudge Rajen

Reputation: 7987

Yes, i had done it but before your answer mate :P :)

    {% for d in data_array %}
                       {% if 1 in d.days %}
                           Monday
                            {% endif %}
                            {% if 2 in d.days %}
                           Tuesday
                            {% endif %}
                           {% if 3 in d.days %}
                           Wednesday
                            {% endif %}
                               {% if 4 in d.days %}
                           Thursday
                            {% endif %}
                            {% if 5 in d.days %}
                           Friday
                            {% endif %}
                            {% if 6 in d.days %}
                           Saturday
                            {% endif %}
                            {% if 7 in d.days %}
                           Sunday
                            {% endif %}
                              {% if not loop.last %},{% endif %}

{% endfor %}

Thanks for your answer :)

Upvotes: 0

Related Questions