0

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),
);

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>

1 Answer 1

5

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 }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</tbody>
</table>
2
  • You say that I have to convert columns arrays in rows array?
    – Rik99
    Aug 19, 2018 at 10:00
  • Yes, as you won't be able to do it easily in twig
    – gogaz
    Aug 19, 2018 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.