如何从Twig模板中的多维四级数组访问值?

时间:2015-12-11 19:36:56

标签: php multidimensional-array twig

如何在树枝中显示多维数组的值?

我的数组是这样的(这是因为我可以使用键轻松排序):

mergedresult = Array( [key01] =>
                        Array ( [key11] => 
                                 Array ( [50] => Array( [id] => 50 [title] => title50 ) ) )              
                      [key02] =>
                        Array ( [key12] => 
                               Array ( [50] => Array( [id] => 50 [title] => title50 ) ) )
);

我想在树枝上访问标题:

{% if mergedresult is not empty %}
<br> mergedresult is not empty <br>
 {% for evarr in mergedresult.all %} {# key=all/AND/OR evarr=array('12'=>array('id'=>12, 'title'=> ...)) #}
      {# <br> for evarr in mergedresult.all <br> #}
    {% if evarr is not empty %} 
         {# <br> if evarr is not empty  <br> #}
        {% for eventarr in evarr %} {# key=12,13,50.. eventarr=array('id'=>12, 'title'=> ...) #}
             {# <br> for eventarr in evarr <br> #}
            {% for event in eventarr %}
                {#  <br> for event in eventarr <br> #}
                <tr> {{ event.title }} </tr>
            {% endfor %} {#  <br> for event in eventarr <br> #}
        {% endfor %} {# <br> for eventarr in evarr <br> #}
    {% endif %}  {#  {% if evarr is not empty %}  #}
  {% endfor %} {# <br> for evarr in mergedresult.all <br> #}
{% endif %} 

但没有显示任何内容。如果我使用注释掉的语句检查,我得到以下结果:

mergedresult is not empty
for evarr in mergedresult.all
if evarr is not empty
for eventarr in evarr
for eventarr in evarr
for evarr in mergedresult.all 
for eventarr in evarr
for eventarr in evarr

似乎twig无法访问title,这是嵌套在第4级多维数组中的值。这可能吗?怎么样?

1 个答案:

答案 0 :(得分:0)

我在文档中找不到hash的限制(对应于php数组的twig数据类型)https://mijingo.com/blog/key-value-arrays-in-twig,但在我的情况下,我无法访问title,因为我使用了太多for循环,因为我的数组是三维的(我也有四维数组&#39; columnresult&#39;并且试图使用三维数组名称来访问它的标题&#39; mergedresult&#39;)。来自第三级多维数组的正确代码访问标题:

{% if mergedresult is not empty %}
    {% for event in mergedresult.all %} {# key=12/50/... evant=array('12'=>array('id'=>12, 'title'=> ...), ..) #}
        <tr> {{ event.title }} </tr>
    {% endfor %} {#  <br> for event in eventarr <br> #}
{% endif %}