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>
Sign up to request clarification or add additional context in comments.

2 Comments

You say that I have to convert columns arrays in rows array?
Yes, as you won't be able to do it easily in twig

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.