I am trying to create a simple html table from nested foreach loops. Actual data will be stored in my database. I want a table will look like:
---------------------
1 | A | red |
---------------------
2 | B | blue |
---------------------
3 | C | yellow |
---------------------
4 | D | orange |
---------------------
$values1 = "1,2,3,4";
$values2 = "A,B,C,D";
$values3 = "red,blue,yellow,orange";
$var1 = explode(',', $values1);
$var2 = explode(',', $values2);
$var3 = explode(',', $values3);
echo '<table>';
foreach ($var1 as $row1) {
echo '<tr>';
echo '<td>'.$row1.'</td>';
foreach ($var2 as $row2) {
echo '<td>'.$row2.'</td>';
}
foreach ($var3 as $row3) {
echo '<td>'.$row3.'</td>';
}
echo '</tr>';
}
echo '</table>';
This code works :
<?php
$values1 = "1,2,3,4";
$values2 = "A,B,C,D";
$values3 = "red,blue,yellow,orange";
$var1 = explode(',', $values1);
$var2 = explode(',', $values2);
$var3 = explode(',', $values3);
echo '<table border="1">';
for($i = 0; $i < count($var1); $i++){
echo '<tr>';
echo '<td>'.$var1[$i].'</td>';
echo '<td>'.$var2[$i].'</td>';
echo '<td>'.$var3[$i].'</td>';
echo '</tr>';
}
echo '</table>';
I think this could help you. Defining your values directly as arrays, and representing them with a foreach loop. It's more like the way mysql_fetch_array represents the records obtained from the database.
$values = [];
$values[] = [1, "A", "red"];
$values[] = [2, "B", "blue"];
$values[] = [3, "C", "yellow"];
$values[] = [4, "D", "orange"];
echo '<table>';
foreach ($values as $value) {
echo '<tr>';
echo '<td>'.$value[0].'</td>';
echo '<td>'.$value[1].'</td>';
echo '<td>'.$value[2].'</td>';
echo '</tr>';
}
echo '</table>';
If you're using $var1
as "base" array, could be handy to check if other arrays also contain the same indexes (same length as $var1
) to avoid PHP warnings.
foreach ($var1 as $key => $value) {
echo '<tr>';
echo '<td>'.$value.'</td>';
echo '<td>'.(isset($var2[$key]) ? $var2[$key] : '').'</td>';
echo '<td>'.(isset($var3[$key]) ? $var3[$key] : '').'</td>';
echo '</tr>';
}