Ansy
Ansy

Reputation: 47

Create html table from arrays

I have managed to create two arrays from database, one for table_headers as follows

$tb_headers=array('010','011','012','013','014','015','016');

And also generated other arrays of table _data from database as follows

$tb_data=array(
array('011','013','014','015'),
array('010','012','014','015','016'),
array('010','011','013','016'),
array('010','011','012','013','014','015','016')
);

How do I generate table of this format??

 th      010 |  011 |   012|   013|    014 |   015 |     016
row1      -  |  011 |   -  |   013|    014 |   015 |     -
row2     010 |   -  |  012 |    - |    014 |   015 |     016
row3     010 |  011 |   -  |   013|     -  |    -  |     016
row4     010 |  011 |  012 |   013|    014 |   015 |     016

I have tried to write this script which is not working as expected

<table style="width:50%;" border="1">
   <tr>
      <?php
      foreach ($tb_headers as $key => $value) {
        echo '<th>'.$value.'</th>';
      }
      echo '</tr>';
      foreach ($tb_headers as $key => $data) {
        echo '<tr>';
        if(!empty($tb_data[$key])&& $tb_data[$key]==$data ){
           echo '<td>'.$tb_data[$key].'</td>';
        }else{
         echo '<td>-</td>'; 
        }
        echo '</tr>';
      }
      ?>   
</table>

Upvotes: 0

Views: 51

Answers (1)

Michael Bolli
Michael Bolli

Reputation: 2159

Try this, which uses the php in_array() function.

<table>
  <tr>
  <?php
  // header
  foreach ($tb_headers as $value) echo '<th>' . $value . '</th>';
  ?>
  </tr>
  <?php
  // content
  foreach ($tb_data as $line => $values) {
    echo '<tr>';
    foreach ($tb_headers as $header) {
      echo '<td>';
      if (in_array($header, $values)) echo $header;
      else echo '-';
      echo '</td>';
    }
    echo '</tr>';
  }
  ?>
</table>

Upvotes: 1

Related Questions