momori14 momori14 - 1 month ago 11
Twig Question

Twig loop through array

I have the following

json_decode
data which is something like this:

Array
(
[0] => Array (
[id] => 218
[startTime] => 1478363400000
[EndTime] => 1478367000000
[c] => Array (
[id] => 1
[code] => A
[name] => Name
[postalCode] => 7TF
[contact] => 1111 242 3144
[email] =>
[website] => /
[fax] =>
[address] => Thisistheaddress
[latitude] => 53.80729675111
[longitude] => -1.5190633535385
[status] => ONLINE
)
[service] => Array (
[id] => 1
[code] => 100
[description] => GENERAL
)
)
[1] => Array ( [id] => 237 [startTime] => 1478593800000 [EndTime] => 1478597400000 [c] => Array ( [id] => 1 [code] => A [name] => Name [postalCode] => 7TF [contact] => 1111 242 3144 [email] => [website] => / [fax] => [address] => Thisistheaddress [latitude] => 53.80729675111 [longitude] => -1.5190633535385 [status] => ONLINE ) [service] => Array ( [id] => 1 [code] => 100 [description] => GENERAL ) )
[2] => Array ( [id] => 199 [StartTime] => 1478187000000 [EndTime] => 1478190600000 [c] => Array ( [id] => 1 [code] => A [name] => Name [postalCode] => 7TF [contact] => 1111 242 3144 [email] => [website] => / [fax] => [address] => Thisistheaddress [latitude] => 53.80729675111 [longitude] => -1.5190633535385 [status] => ONLINE ) [service] => Array ( [id] => 1 [code] => 100 [description] => GENERAL ) )
)


My question is how do i iterate this so i could get the [startTime] , [name] and [address] in twig. I have tried the following:

{% for key,a in TimeInfo|keys %}
Key : {{ key }}
{% endfor %}


The result above is just giving me a key, I also tried the following:

{% for a in TimeInfo %}
{{ a.name }}
{% endfor %}


The above result is an error. Appreciate the help :)

Answer

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 %}