I'm trying to learn how to loop through a nested array and create a PHP table.
I cannot figure out how to loop through so that each array is in its own <tr> tag.
I used a for loop to create a <tr> for each array. However I think I miss understand how to do this. It is looping through both arrays before creating a new <tr>.
PHP Code:
<?php
//Lets make a table
$rows = array(
array(
'color' => 'red',
'make' => 'Ferrari',
'price' => 3000
),
array(
'color' => 'blue',
'make' => 'BMW',
'price' => 1000
)
);
?>
<table border='1'>
<tr>
<th>Colour</th>
<th>Make</th>
<th>Price</th>
</tr>
<?php
for($i = 0; $i < count($rows); $i++){
echo '<tr>';
foreach($rows as $rowkey => $row){
echo '<td>' . $row['color']. '</td>';
echo '<td>' . $row['make'] . '</td>';
echo '<td>' . $row['price'] . '</td>';
}
echo '</tr>';
}
?>
</table>
Result:
<table border='1'>
<tr>
<th>Colour</th>
<th>Make</th>
<th>Price</th>
</tr>
<tr>
<td>red</td>
<td>Ferrari</td>
<td>3000</td>
<td>blue</td>
<td>BMW</td>
<td>1000</td>
</tr>
<tr>
<td>red</td>
<td>Ferrari</td>
<td>3000</td>
<td>blue</td>
<td>BMW</td>
<td>1000</td>
</tr>
</table>
How do I loop through this sort of array and create a new <tr> per nested array?