I have an array of this type:

Array ( [data] => Array ( [0] => tratata [1] => blabla ) [data_key] => Array ( [0] => the first key [1] => the second one ) ) 

And I tried to display it like this:

 {% for key, value in L10_DATA %} <tr> <th> {{ value.data_key }} </th> <td> {{ value.data }} </td> </tr> {% endfor %} 

But this code does not work: c Help me please

  • you merge it first into one array, and then work $data = array_combine($x['data_key'], $x['data']) - teran
  • or the second option array_map(null, $x['data'], $x['data_key']) . It is not necessary to load the template with logic, which should be done in the controller, prepare the data initially so that it is convenient to work with them when outputting, and not crutches. - teran

2 answers 2

Here is a working example.

 {% set data = ['заголовок 1', 'заголовок 2'] %} {% set data2 = ['значение 1', 'значение 2'] %} {% for key, value in data %} <tr> <th> {{ value }} </th> <td> {{ data2[key] }} <td> </tr> {% endfor %} 

The for loop works in such a way that it passes the corresponding values ​​to key, and value.

key - the key of the current iteration array

value - the value of the current iteration

If your array keys are the same, then in my example you can see how to correctly output the data.

    You can try a little differently, your array element is an array, I see the tags <tr> , <th> and <td> , which means this is a table, try this:

     {% set data = [ {'data': ['tratata', 'blabla']}, {'data_key': ['the first key', 'the second one']} ] %} <table> <tr> {% for index in 0..data|length-1 %} {% for key, values in data[index] %} {% if key == 'data_key' %} {% for value in values %} <th>{{ value }}</th> {% endfor %} {% endif %} {% endfor %} {% endfor %} </tr> {% for index in 0..data|length-1 %} {% for key, values in data[index] %} {% if key == 'data' %} <tr> {% for value in values %} <td>{{ value }}</td> {% endfor %} </tr> {% endif %} {% endfor %} {% endfor %} </table> 

    Then you will get this markup at the output:

     <table> <tr> <th>the first key</th> <th>the second one</th> </tr> <tr> <td>tratata</td> <td>blabla</td> </tr> </table>