0

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?

1
  • 3
    Easy. In your controller transform the array into one that matches your twig requirements.
    – Cerad
    Apr 28, 2015 at 21:58

1 Answer 1

1

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.