code_learn code_learn - 1 year ago 106
PHP Question

Echo html table from PHP array

I'm learning php and I'm stuck with one task..
I have an array looking like this:

$data[1]["First"] = "Iva";
$data[1]["Last"] = "Ivić";
$data[1]["Date"] = "2016-09-29";
$data[1]["Paid"] = "Yes";

$data[2]["First"] = "Petar";
$data[2]["Last"] = "Perić";
$data[2]["Date"] = "2016-02-08";
$data[2]["Paid"] = "No";

$data[3]["First"] = "Tomo";
$data[3]["Last"] = "Tomić";
$data[3]["Date"] = "2015-08-22";
$data[3]["Paid"] = "Yes";

I need to echo HTML table from this Array. On the value ['Paid'], html table should output select field and showing current value as selected.
Also, first column of the table should assign #ID number.

So far, I've managed to create the table, but I can't figure out how to count and echo # and getting the select field to work. Second value doesn't work for me.

<table border="1" align="center" width="80%">
<tr bgcolor="yellow">
<th>ID #</th>

foreach ( $data as $info )
// date transform
$date = explode('-', $info['Date']);

echo '<tr align="center" bgcolor="#f6f6f6">';
echo ' <td>' '</td>';// How to count #IDs starting from 1?
echo '<td>'. $info['First'] .'</td>';
echo '<td>'. $info['Last'] .'</td>';
echo '<td>'. $date[2].'.'.$date[1].'.'.$date[0].'.</td>';
//echo '<td>'. $info['Paid'] .'</td>';

echo '<td>';
echo '<select name="Paid">';
echo '<option value="0" selected>'. $info['Paid'] .'</option>';
echo '<option value="1">'. $info['Paid'] .'</option>';//This is where I'm stuck
echo '</select>';
echo '</td>';
echo '</tr>';


Answer Source

There are plenty of loops you can use to achieve this, the easiest case here is the foreach() loop.

<!-- conditional loops -->
<?php foreach($data as $single): ?>

    <!-- shorthand PHP statement to echo the result -->
    <td> <?= $single['First']; ?> </td>

<?php endforeach; ?>

Note - Array index's start at 0, not 1. So the first value would be $data[0]['First']

If you're creating tables for each array inside it, you can use nested loops like this:

<?php for($i = 0; $i <= count($data); $i++):
    foreach($data[$i] as $key => $val): ?>
            <!-- ternary expression -->
            <tr> <?= ($key == "First") ? $val : ""; ?> </tr>
    <?php endforeach;

If you prefer a different approach, you can use while() loops to achieve the same idea:

<?php $i = 0;
while($i != count($data)): ?>
    <tr> <?= $data[$i++]['First']; ?> </tr>
<?php endwhile;

Note for future - It's a lot easier working with bool datatypes rather than 'yes', 'no' strings. For example:

$paid = true;
echo ($paid) ? 'selected' : '';

rather than something like:

echo ($paid == 'No') ? '' : 'selected';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download