Skip to content

Instantly share code, notes, and snippets.

@angelorocha
Last active December 28, 2022 15:02
Show Gist options
  • Save angelorocha/bdd10af73d047709553ef225500fe993 to your computer and use it in GitHub Desktop.
Save angelorocha/bdd10af73d047709553ef225500fe993 to your computer and use it in GitHub Desktop.
Multidimensional arrays to html table
<?php
$arr = [
'key_1' => [
'key_1_val_1',
'key_1_val_2',
'key_1_val_3',
'key_1_val_4',
],
'key_2' => [
'key_2_val_1',
'key_2_val_2',
'key_2_val_3',
'key_2_val_4',
],
'key_3' => [
'key_3_val_1',
'key_3_val_2',
'key_3_val_3',
'key_3_val_4',
],
'key_4' => [
'key_4_val_1',
'key_4_val_2',
'key_4_val_3',
'key_4_val_4',
],
];
$head = [];
$body = [];
$t_body = [];
foreach ( $arr as $key => $val ) {
$head[] = $key;
$row = count( $val );
$body[] = $val;
}
$index = 0;
for ( $c = 0; $c < $row; $c ++ ) {
foreach ( $body as $b ) {
$t_body[ $index ][] = $b[ $index ];
}
$index ++;
}
?>
<table border="1">
<thead>
<tr>
<?php foreach ( $head as $th ): ?>
<th><?php echo $th ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ( $t_body as $tr ): ?>
<tr>
<?php foreach ( $tr as $td ): ?>
<td><?php echo $td; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment