How to make dynamic table on php codeigniter

2019-08-20 16:53发布

问题:

i'm new on using codeigniter, i want to ask how to make dynamic table so when i select data from anytable form database it can be fit with the table, even the field is different.

so, in normally i show table like this :

<table class="table table-striped">
    <thead>
      <tr>
        <th scope="col">#Number</th>
        <th scope="col">Field</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $no = 1;
       foreach ($data as $row) {?>
          <tr>
            <th scope="row"><?php echo $no++?></th>
            <td><?php echo $row->COLUMN_NAME ?></td>
          </tr>
      <?php } ?>
    </tbody>
</table>

but the problem when i using 3 field or more field it can't be fit, so any suggestion for it?

回答1:

Your problem:

You are fetching data from database.

And want to display it in table but, not sure how many columns are there.

Solution:

Say, you have a multi-dimensional array with n records.

First get the first element (which is a database row, a table row)

Get count of it.

Now loop over the array.

Use foreach() language construct.

It will take care of every thing.

Note: This solution assumes that the individual array (database records) are having same number of columns.

<?php
if (! empty($arr)) {
  foreach ($arr as $elem) {
?>
    <tr>
<?php
   if (! emtpy($elem)) {
     foreach($elem as $td) {
?>
     <td><?php echo $td;?></td>
<?
     }
   }
   </tr>
<?   
  }
}