使用SMARTY基于第一个键显示第二层数组

时间:2016-10-07 10:38:26

标签: php multidimensional-array html-table smarty multi-index

我有问题将以下数组显示在表格中。我们的想法是根据第一个数组显示水平数据,但第二个数组也应该被访问并显示为水平。

数组(为了显示目的,我颠倒了数组):

    Array ( 
    [3] => Array ( 
         [name] => Joop 
         [details] => Array ( 
                      [length] => 184
                      [weight] => 86
                      ...
                      ) 
         [year] => 1984
         [university] => Harvard 
         [class_id] => 37 
         [group_id] => 14 
         ) 
    [2] => Array ( 
         [name] => Tim 
         [details] => Array ( 
                      [length] => 169
                      [weight] => 74
                      ...
                      ) 
         [year] => 1977
         [university] => MIT 
         [class_id] => 37 
         [group_id] => 14 
         ) 
    [1] => Array ( 
         [name] => Kelly 
         [details] => Array ( 
                      [length] => 164 
                      [weight] => 51
                      ...
                      ) 
         [year] => 1982
         [university] => MIT 
         [class_id] => 37 
         [group_id] => 14 
         ) 
    [0] => Array ( 
         [name] => Alex 
         [details] => Array ( 
                      [lenght] => 172
                      [weight] => 79
                      ...
                      ) 
         [year] => 1979
         [university] => Harvard
         [class_id] => 37 
         [group_id] => 14 
         )

我希望将它显示在HTML表格中,如下所示:

Name | Joop | Tim | Kelly | Alex
Length | 184 | 169 | 164 | 172
weight | 86 | 74 | 51 | 79
...
...
Year | 1984 | 1977 | 1982 | 1979
university | Harvard | MIT | MIT | Harvard

我已经在我的模板中使用foreach和loop组合尝试了它,但我无法正确显示详细信息部分。

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试循环第一个数组的键,然后再遍历每一个

{foreach $arr.0 as $row=>$wathever}
<tr><td>{$row}</td>
{foreach $arr as $col}
<td>{$col.$row}</td>
{/foreach}
</tr>
{/foreach}

答案 1 :(得分:0)

找到解决方案如下:

{foreach key=key item=item from=$arr}<th>{$item.name}</th>
{/foreach}
{foreach item=item  key=key from=$arr.0.details}
  <tr><td>{$key}</td>
    {section name=arrloop loop=$arr}
    <td>{$arr[arrloop].details.$key}</td>
    {/section}
  </tr>
{/foreach}