2010-08-18 59 views
0
<?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
$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>'; 
} 
在這種情況下
+0

我reuturn $ result_from_db_query =陣列( 1 =>數組( '頭1'=> 'AAA', '標題2'=> 'BBB', 'header3'=> 'CCC') ,\t 2 => array('header1'=>'aaa2','header2'=>'bbb2','header3'=>'ccc2') ); – kn3l 2010-08-18 14:31:18

+0

請使用此密碼重試 – 2010-08-18 14:35:28

+0

!非常感謝您的簡短code.it現在的作品, – kn3l 2010-08-18 14:57:15