If you have data that is stored in row-major order (that is, your data is an array of rows, rather than columns, of data), you must keep track of the columns to print. This is a typical way to receive data from a MySQL database.
You can do this by looking at your first row, using $columns = array_keys($row), or simply hard-code the column keys if they are known in advance like I have done in the following example.
<?php
$data = [
[
"name" => "Alice",
"email" => "[email protected]",
"home_address" => "Alice Lane 61"
],
[
"name" => "Bob",
"age" => 16,
"home_address" => "Bob St. 42"
]
];
$columns = [ "name", "age", "email", "home_address" ];
?>
<html>
<body>
<table>
<tr>
<?php foreach($columns as $column) { ?>
<th><?php echo $column; ?></th>
<?php } ?>
</tr>
<?php foreach ($data as $row) { ?>
<tr>
<?php foreach($columns as $column) { ?>
<td>
<?php
if (isset($row[$column])) {
echo $row[$column];
} else {
echo "N/A";
}
?>
</td>
<?php } // end $column foreach ?>
</tr>
<?php } // end $row foreach ?>
</table>
</body>
</html>
Note that not all rows have the same columns here. This is handled in the if-statement in the table.
This example outputs:
<html>
<body>
<table>
<tr>
<th>name</th>
<th>age</th>
<th>email</th>
<th>home_address</th>
</tr>
<tr>
<td>Alice </td>
<td>N/A </td>
<td>[email protected] </td>
<td>Alice Lane 61 </td>
</tr>
<tr>
<td>Bob </td>
<td>16 </td>
<td>N/A </td>
<td>Bob St. 42 </td>
</tr>
</table>
</body>
</html>