简体   繁体   English

在Twig挑战中显示PHP数组

[英]Display PHP array in Twig challenge

I have an array in PHP consisting of 22 elements. 我有一个由22个元素组成的PHP数组。 I want to render it on the page using TWIG. 我想使用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. 我希望键(名称一,名称二等)位于一个单元格中,键“数字”位于另一个单元格中,其余键(0、1,2等)也位于单独的单元格中。 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. 我可以写{{value[0]}} ,我将获得键的值,但是数组中此类键的数量不同,因此我想找到列出所有键的方法。 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? 我该如何实现?

In your structure value['number'] is an array then you should do something like this to avoid wrong offset error : 在您的结构中, value['number']是一个数组,那么您应该执行以下操作以避免错误的offset错误:

{{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). 就像Cerad在评论中所说的那样,还有另一种解决方案:迭代控制器中的worker数据(或者更好地在控制器调用的服务中),然后合并一个易于在您的迭代中使用的自定义PHP对象(DTO)。视图(您将在树枝中传递此dto)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM