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?
Try this, loose the outer for loop:
<?php
$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 foreach ($rows as $key => $row): ?>
<tr>
<td><?= $row['color'] ?></td>
<td><?= $row['make'] ?></td>
<td><?= $row['price'] ?></td>
</tr>
<?php endforeach; ?>
</table>
You should choose and use one of two your loops:
Either:
for($i = 0; $i < count($rows); $i++){
echo '<tr>';
echo '<td>' . $rows[$i]['color']. '</td>';
echo '<td>' . $rows[$i]['make'] . '</td>';
echo '<td>' . $rows[$i]['price'] . '</td>';
echo '</tr>';
}
Or:
foreach($rows as $rowkey => $row){
echo '<tr>';
echo '<td>' . $row['color']. '</td>';
echo '<td>' . $row['make'] . '</td>';
echo '<td>' . $row['price'] . '</td>';
echo '</tr>';
}
because now you loop over you array twice:
for
loop foreach
loop
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.