简体   繁体   English

从数组创建 html 表

[英]Create html table from arrays

I have managed to create two arrays from database, one for table_headers as follows我设法从数据库创建了两个数组,一个用于 table_headers,如下所示

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

And also generated other arrays of table _data from database as follows并且还从数据库中生成了表 _data 的其他数组,如下所示

$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>

Try this, which uses the php in_array() function.试试这个,它使用 php in_array()函数。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM