Search code examples
phpmysqldynamictabular

Different number of columns each row in a table with PHP


I would like to make a table with different numbers of cols with PHP and with data from mysql.

To make this possible I think an easy way out is to first print a table with rows and within them rows make a new table with random number of columns. I know this is not a recommended thing to do but I need it this way.

When I do it all the cells got the same value.

Can anyone please help me out?

Example:

enter image description here


Solution

  • Please try code as given below

    <?php
      $rows = array();
      $rows[0][0] = 'A';
      $rows[0][1] = 'B';
      $rows[0][2] = 'C';
      $rows[1][0] = 'D';
      $rows[1][1] = 'f';
      $rows[2][0] = 'f';
      $rows[2][1] = 'k';
      $rows[2][2] = 'f';
      $rows[2][3] = 'j';
      $rows[3][0] = 'j';
      $total_rows = count($rows);
    
       echo "<table border='2'>";
    
        for($i = 0;$i < $total_rows; $i++){
        echo "<tr>";
          foreach($rows[$i] AS $col){
            echo "<td>";
                echo $col;
           echo "</td>";
          }
        echo  "</tr>";
       }
    echo "</table>";
    

    Here first index of array is showing row number and second index showing column number of table.

    thanks