简体   繁体   中英

Convert php array to table with twig

Hi I need to build a table with twig from a php array, I would like to use the array keys as header for each column.

this is the array

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

This is what I've tried so far

<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>

This is the result

0   1
2C  57  Via monteverde 45   Andrea
4E  55  Via monteverde 45   Andrea

You can do something like this by fetching keys of the first array of 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>

Your issue is that the keys you want to use as headers exist as the keys in the second-depth array, not the primary array. Meaning that you have to loop those keys instead of the keys in the first array.

Using prova.0 to get the first element, will then result in the keys being of the sub-array - which you can then loop as before.

{% for titolo in prova|first|keys %}
    <th>{{titolo}}</th>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM