简体   繁体   English

如何在树枝中正确循环三维数组?

[英]How to properly loop three dimensional array in twig?

I have an array setup like so; 我有一个像这样的阵列设置; and I cant seem to loop through the values with twig: 我似乎无法用树枝循环遍历这些值:

array (size=1)
  'hash' => 
    array (size=7)
      0 => 
        array (size=4)
          'key1' => "val"
          'key2' => "val"
          'key3' => "val"
          'key4' => "val"
      1 => 
        array (size=4)
          'key1' => "val"
          'key2' => "val"
          'key3' => "val"
          'key4' => "val"
      ...

The template code I'm using (in its nth iteration): 我正在使用的模板代码(在第n次迭代中):

  {% for i in hash %}
    {% for j in i %}
      <td>{{ j.key1 }}</td>
      <td>{{ j.key2 }}</td>
      <td>{{ j.key3 }}</td>
      <td>{{ j.key4 }}</td>
    {% endfor %}
  {% endfor %}

I keep getting Array to string conversion errors with the above twig template code. 我继续使用上面的twig模板代码获取Array to string conversion错误。

With the help of vijay4vijju and his reference to dump I was able to loop over the array. 在vijay4vijju和他对dump引用的帮助下,我能够遍历数组。

Only a single loop was needed: 只需要一个循环:

{% for key,val in hash %}
  <tr>
    <td>{{ val.key1 }}</td>
    <td>{{ val.key2 }}</td>
    <td>{{ val.key3 }}</td>
    <td>{{ val.key4 }}</td>
  </tr>
{% endfor %}

I would have selected his answer but it technically wasn't the answer, and dump was just a reference to the dump manual. 我会选择他的答案但技术上不是答案,而dump只是对dump手册的引用。

To enable debugging in twig I used: 为了在twig中启用调试,我使用了:

$twig = new Twig_Environment($loader, array(
    'debug' => true,
));
$twig->addExtension(new Twig_Extension_Debug());

To troubleshoot this issue I used: 要解决此问题,我使用了:

{% for key,val in hash %}
  <pre>{{ dump(val) }}</pre>
  <tr>
    <td>{{ val.key1 }}</td>
    <td>{{ val.key2 }}</td>
    <td>{{ val.key3 }}</td>
    <td>{{ val.key4 }}</td>
  </tr>
{% endfor %}

Try this. 尝试这个。 I am not sure 我不确定

  {% for key,value in hash %}
          {% for key1,value1 in value %}
               Value1 : {{ dump(value1) }}
                {% for key2,value2 in value1 %}
                     Value1 : {{ value2 }} 
                {% endfor %} 
         {% endfor %}
    {% endfor %}

dump will print the data from the array: dump将打印数组中的数据:

Refer dump 请参阅转储

I used this for printing multi-dimensional array in twig, hopefully it will work. 我用它在树枝上打印多维数组,希望它能起作用。

{% for item in hash %}
    {% for firstLevelItem in item %}
        <ul>
            <li>{{ firstLevelItem.comments }}</li>
        </ul>
    {% endfor %}
{% endfor %}

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

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