想要根据表头的顺序动态显示行

时间:2010-08-18 13:36:24

标签: php

<?php
$header = array('header1','header2','header3');
?>
<table>
<thead>
    <tr>
<?php 
    for($i=0;$i<=count($header);$i++){?>
        <th ><?php echo $header[i];?></th>
    <?php } ?>
    </tr>
</thead>
<?php foreach($result_from_db_query as $key=>$val){?>
 <tr><td><?php echo $val['Column1']?></td><td><?php echo $val['Column2']?></td><td><?php echo $val['Column3']?></td></tr>
?>
</table>
Want to dynamic the row display depend on order of table header
for example if 
$header = array('header1','header2','header3')
the output should like this
<table>
<thead>
    <tr>
        <th >Header 1</th>
        <th >Header 2</th>
        <th >Header 3</th>
    </tr>
</thead>
<tr><td>Column11</td><td>Column21</td><td>Column31</td></tr>
<tr><td>Column12</td><td>Column22</td><td>Column32</td></tr>
<tr><td>Column13</td><td>Column23</td><td>Column33</td></tr>
<tr><td>Column14</td><td>Column24</td><td>Column34</td></tr>
</table>
BUT 
if 
$header = array('header3','header2','header1')

the output should like this

<table>
<thead>
    <tr>
        <th >Header 1</th>
        <th >Header 2</th>
        <th >Header 3</th>
    </tr>
</thead>
<tr><td>Column31</td><td>Column21</td><td>Column11</td></tr>
<tr><td>Column32</td><td>Column22</td><td>Column12</td></tr>
<tr><td>Column33</td><td>Column23</td><td>Column13</td></tr>
<tr><td>Column34</td><td>Column24</td><td>Column14</td></tr>
</table>

等等。 任何人都知道如何用PHP代码来定义数据结构。

1 个答案:

答案 0 :(得分:1)

$header = array('header1','header2','header3');

foreach($result_from_db_query as $val) {
   echo '<tr>';
   foreach($header as $column) { 
      echo '<td>',$val[$column],'</td>';
   }
   echo '</tr>';
}