Shepherd
Shepherd

Reputation: 293

Display PHP array in Twig challenge

I have an array in PHP consisting of 22 elements. I want to render it on the page using TWIG. Here is the structure:

array(22) {
  ["Name One"]=>
  array(4) {
    [0]=>
    string(27) "2015-04-03 - 2015-04-03 (1)"
    ["number"]=>
    array(3) {
      [0]=>
      string(2) "26"
      [1]=>
      string(2) "26"
      [2]=>
      string(2) "26"
    }
    [1]=>
    string(27) "2015-04-13 - 2015-04-15 (3)"
    [2]=>
    string(27) "2015-04-27 - 2015-04-27 (1)"
  }
  ["Name Two"]=>
  array(2) {
    [0]=>
    string(27) "2015-04-07 - 2015-04-07 (1)"
    ["number"]=>
    array(1) {
      [0]=>
      string(2) "21"
    }
  }
(...)

I want to render it in a table. I want the keys (Name One, Name Two etc.) to be in one cell, the key 'number' in other cell and rest of the keys (0,1,2 etc.) also in seperate cells. I can write {{value[0]}} and I will get the value of the key, but there is different number of such keys in the array so I want to find the method that will list all the keys. I'm trying to do this like this:

{% for key,value in workers %}
    <tr><td>{{key}}</td><td>{{value[0]}}</td><td>{{value['number']}}</td></tr>
{% endfor %}

but there's an error on 'number' key (wrong offset). Based on the above structure I want to achieve something like this:

<tr>
  <td>Name One</td>
  <td>2015-04-03 - 2015-04-03 (1)</td>
  <td>2015-04-13 - 2015-04-15 (3)</td>
  <td>2015-04-27 - 2015-04-27 (1)</td>
  <td>26</td>
</tr>
<tr>
  <td>Name Two</td>
  <td>2015-04-07 - 2015-04-07 (1)</td>
  <td>21</td>
</tr>

How can I achieve this?

Upvotes: 0

Views: 153

Answers (1)

Nico
Nico

Reputation: 3566

In your structure value['number'] is an array then you should do something like this to avoid wrong offset error :

{{value['number'][0]}}

Also as Cerad said in his comment, there is another solution : iterate on your workers data in your controller (or better in a service called by your controller) and then hydrate a custom PHP object (DTO) that will be easy to iterate in your view (you will pass this dto in your twig).

Upvotes: 1

Related Questions