What would be the best way to print an HTML table with an array of arrays in php? Each array key would be the head of the table, and the sub-array items the table cells.
arr = [
key_1 ->
- key_1_val_1
- key_1_val_2
- key_1_val_3
key_2 ->
- key_2_val_1
- key_2_val_2
- key_2_val_3
]
Expected output:
<table>
<tr>
<td>key_1</td>
<td>key_2</td>
</tr>
<tr>
<td>key_1_val_1</td>
<td>key_2_val_1</td>
</tr>
...
</table>
Any idea?
Tnx
Not success:
<table>
<thead>
<tr>
<?php foreach ( array_keys( $get_cards ) as $head ): ?>
<th><?php esc_html_e( get_the_title( $head ) ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<tr>
<?php foreach ( $get_cards as $cols ): ?>
<?php $row_end = count( $get_cards ); ?>
<?php $colum_end = count( $cols ); ?>
<?php $count_rows ++; ?>
<?php foreach ( $cols as $col ): ?>
<?php $count_columns ++; ?>
<td>1</td>
<?php endforeach; ?>
<?php if ( $count_rows % 2 === 0 ): ?>
<?php endif; ?>
<?php $count_columns = 0; ?>
<?php endforeach; ?>
<?php $count_rows = 0; ?>
</tr>
</tbody>
</table>
Solved.
This is my solution: https://gist.github.com/angelorocha/bdd10af73d047709553ef225500fe993
2
Answers
The code of your project is to create a new array for creating a comparative table. We can do it by manipulating index in your case.
This is the main logic for creating a new array.
this is the full code.
Use a set of nested loops to transpose the multidimensional array data (as well as transferring the first level keys as the new first row of data).
Then use a basic loop to print the rows as html. The way
implode()
is used, it won’t matter if the number of columns changes — it will create as many columns as are needed.Code: (Demo)