Twig for loop for arrays with keys
I found the answer :
{% for key,value in array_path %}
Key : {{ key }}
Value : {{ value }}
{% endfor %}
Twig loop through array
Your second loop attempt was close but the name
key doesnt exists on the initial array keys. id, startTime, EndTime, c, service
. The name
key appears to be nested under c
. So you should be able to access it like:
{% for a in TimeInfo %}
The start time is: {{ a.startTime }}
The Name is: {{ a.c.name }} {# notice we access "c" then "name" #}
{% endfor %}
foreach ( $response as $key = $element ) in Twig
Based on your data and the comments, I'm not even sure you'd need the key to solve your problem
{% for item in items if item.url == uri %}
{{ item.count }}
{% endfor %}
demo
EDIT
As of twig 2.10.0 it's deprecated to use an if
directly inside the for
-statement, now you either place the if
inside the block or use the filter filter
{% for item in items %}
{% if item.url == uri %}
{{ item.count }}
{% endif %}
{% endfor %}
{% for item in items|filter(v => v.url == uri) %}
{{ item.count }}
{% endfor %}
Twig for loop from array
dataTable
is 0-indexed array and does not have name
property. But each of its subarrays has this property, so I suppose you need this code (as data
represents each item of datatTable
):
<label class="main-name-list-form">{{ data.name }}</label>
Reference array from key in for loop with Twig
How about this:
{% for i in range(0, limit-1) %}
{% if data[i] is defined %}
{{ data[i] }}
{% endif %}
{% endfor %}
How use variable as key in Twig's for loop?
The syntax is fields_vars [ foo ]
. I made you an example on a online ifddle
Fiddle: https://twigfiddle.com/tdau2h
{% set fields_vars =["dogs","cats","birds"] %}
{% set foo = 123 %}
{# value #}
{% if foo in fields_vars %}
{{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
{{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}
{# key #}
{% if fields_vars[foo] is defined %}
key {{ foo }} is in array {{ fields_vars|join(', ') }}
{% else %}
key {{ foo }} is not in array {{ fields_vars|join(', ') }}
{% endif %}
Related Topics
How to Get User Timezone Using Jquery
Use Git Smudge/Clean to Replace File Contents
How to Make a Cascading Drop Down List in PHP Using Jquery
How to Download Large Files Through PHP Script
Saving Images in Database MySQL
How to Execute a Stored Procedure in PHP Using SQLsrv and "" Style Parameters
Why Is Calling a Function (Such as Strlen, Count etc) on a Referenced Value So Slow
JavaScript Function Post and Call PHP Script
PHP Warning: Exec() Unable to Fork
How to Select Multiple Rows from MySQL with One Query and Use Them in PHP
PHP Run Once and Insert Twice in MySQL Database
$_Post Is Empty After Form Submit
Best Way to Handle Errors on a PHP Page
Update Without Touching Timestamps (Laravel)
PHP Files Are Downloaded by Browser Instead of Processed by Local Dev Server (Mamp)