Maurice Greenland
Maurice Greenland

Reputation: 315

PHP - Create a table from data in nested array

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?

Upvotes: 1

Views: 1113

Answers (2)

u_mulder
u_mulder

Reputation: 54841

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:

  • first time with for loop
  • second time with a foreach loop

Upvotes: 3

ajmedway
ajmedway

Reputation: 1492

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>

Upvotes: 3

Related Questions