将 PHP 数组渲染为 TWIG 中的表格 [英] Render a PHP array as a table in TWIG
本文介绍了将 PHP 数组渲染为 TWIG 中的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 PHP 中有一个具有这种结构的数组
I have an array in PHP with this structure
$array = array(
'head1' => array(1,2,3),
'head2' => array(4,5,6),
'head3' => array(7,8,9),
);
如何在具有这种结构的 twig 中创建 HTML 表,其中 $array 变量的每个数组都是一列,数组键是表头?
How can I create an HTML table in twig which have this structure where every array of the $array variable is a column and array keys are table headers?
<table>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
</tr>
<tr>
<td>1</td>
<td>4</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td>8</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>9</td>
</tr>
</table>
推荐答案
您可以使用内置过滤器 键
.如果它不完全符合您的预期,那是因为您的数组需要在将其传递给 twig 之前在 PHP 中进行处理
You can do it using the builtin filter keys
. If it's not exactly what you expected, then it is because your array needs to be processed in PHP before passing it to twig
<table>
<thead>
<tr>
{% for key in array|keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for sub_array in array %}
<tr>
{% for value in sub_array %}
<td>{{ value }}</th>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
这篇关于将 PHP 数组渲染为 TWIG 中的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文