使用树枝将 php 数组转换为 table
Convert php array to table with twig
嗨,我需要用 php 数组中的树枝构建一个 table,我想将数组键用作每列的 header。
这是数组
Array (
[0] => Array (
[building_code] => 2C
[building_unit_id] => 57
[address] => Via monteverde 45
[name] => Andrea
)
[1] => Array (
[building_code] => 4E
[building_unit_id] => 55
[address] => Via monteverde 45
[name] => Andrea
)
)
这是我目前尝试过的方法
<table>
<thead>
<tr>
{% for titolo in prova|keys %}
<th>{{titolo}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in prova %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</th>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
这是结果
0 1
2C 57 Via monteverde 45 Andrea
4E 55 Via monteverde 45 Andrea
你可以通过获取 prova
的第一个数组的键来做这样的事情
<table>
<thead>
<tr>
{% for titolo in prova.0|keys %}
<th>{{titolo}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in prova %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</th>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
您的问题是您想要用作 headers 的键作为键存在于 second-depth 数组中,而不是主数组中。这意味着您必须循环这些键而不是第一个数组中的键。
使用 prova.0
获取第一个元素,然后将导致 keys
成为 sub-array - 然后您可以像以前一样循环。
{% for titolo in prova|first|keys %}
<th>{{titolo}}</th>
{% endfor %}
嗨,我需要用 php 数组中的树枝构建一个 table,我想将数组键用作每列的 header。
这是数组
Array (
[0] => Array (
[building_code] => 2C
[building_unit_id] => 57
[address] => Via monteverde 45
[name] => Andrea
)
[1] => Array (
[building_code] => 4E
[building_unit_id] => 55
[address] => Via monteverde 45
[name] => Andrea
)
)
这是我目前尝试过的方法
<table>
<thead>
<tr>
{% for titolo in prova|keys %}
<th>{{titolo}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in prova %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</th>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
这是结果
0 1
2C 57 Via monteverde 45 Andrea
4E 55 Via monteverde 45 Andrea
你可以通过获取 prova
<table>
<thead>
<tr>
{% for titolo in prova.0|keys %}
<th>{{titolo}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in prova %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</th>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
您的问题是您想要用作 headers 的键作为键存在于 second-depth 数组中,而不是主数组中。这意味着您必须循环这些键而不是第一个数组中的键。
使用 prova.0
获取第一个元素,然后将导致 keys
成为 sub-array - 然后您可以像以前一样循环。
{% for titolo in prova|first|keys %}
<th>{{titolo}}</th>
{% endfor %}