2

I am trying to create a table with HTML and PHP that displays a different array (array will eventually come from a DB table) in each column of the HTML/PHP table. There are 3 Columns.

<table class="table-styling">

          <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
          </tr>
         
          <?php
          $arr = array(1, 2, 3, 4);
          foreach ($arr as $value) {
          echo '<tr>'.
               '<td>'.$value.'</td>';
          }

          $arr2 = array(5, 6, 7, 8);
          foreach ($arr2 as $value2) {
          echo '<td>'.$value2.'</td>';  
          } 

          $arr3 = array(9, 10, 11, 12);
          foreach ($arr3 as $value3) {
          echo '<td>'.$value3.'</td>'.'</tr>';  
          } 
          ?>

</table>

CSS

.table-styling{
  border-collapse: collapse;
  width: 100%;
  color: #eb4034;
  font-family: monospace;
  font-size: 15px;
  text-align: left;
}
.table-styling th{
  background-color: #eb4034;
  color: white
}

Current Result

Column 1 Column 2 Column 3
1
2
3
4 5 6 7 8 9
10
11
12

Expected Result

Column 1 Column 2 Column 3
1 5 9
2 6 10
3 7 11
4 8 12
2

1 Answer 1

0

The issue is not about the database.
You should check your logic about how you use for-loops.
Because the logic to use for-loops in your mind is wrong.

Please let me explain to you why.

In the fourth row of your wrong result are
4 -- 5,6,7,8 -- 9.
But why? Let me explain to you.

There are three loops in your code.

At the end of the first loop, your code makes 4.
In the second loop, your code makes 5,6,7,8.
At the beginning of the third loop, your code makes 9.

And then echo to finish the fourth row.

This is why the fourth row shows 4 5 6 7 8 9.

You want to use 3 numbers of 1-dimension for-loop to show a 2-dimension table.
But this is a logical error in your thinking.
How your echo a table is by the 2-level for-loops (not 1-level for-loop).

For example, you may need 2-dimension array.
And do some code like the following.

$myArray = array(
    array(1, 5, 9),
    array(2, 6, 10),
    array(3, 7, 11),
    array(4, 8, 12),
);

$out = "<table>";
foreach($myArray as $row) {
    $out .= "<tr>";
    foreach ($row as $cell) {
        $out .= "<td>" . $cell . "</td>";
    }
    $out .= "</tr>";
}
$out .= "</table>";


echo $out;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.