arrays - How to create dynamic header for tables in php -
arrays - How to create dynamic header for tables in php -
my array -
$myfinal = array( 13 => array ( 5 => 85, 4 => 75, 3 => 65, 2 => 55 ), 12 => 11, 7 => 100 );
this want generate(table) dynamically -
required output - http://jsfiddle.net/lckw6/
<table cellspacing="1" cellpadding="4" border="3" bgcolor="#f5f5f5"> <tbody> <tr bgcolor="#99cccc"> <th colspan="4">13</th> <th colspan="0">12</th> <th colspan="0">7</th> </tr> <tr bgcolor="#99cccc"> <th width="70">5</th> <th width="70">4</th> <th width="70">3</th> <th width="70">2</th> <th width="70">no subcat</th> <th width="70">no subcat</th> </tr> <tr align="right"> <td>85</td> <td>75</td> <td>65</td> <td>55</td> <td>11</td> <td>100</td> </tr> </tbody></table>
my code try, tried first tr , th rest confused loop :(
<?php $myfinal = array( 13 => array ( 5 => 85, 4 => 75, 3 => 65, 2 => 55 ), 12 => 11, 7 => 100 ); ?> <table cellspacing="1" cellpadding="4" border="3" bgcolor="#c3cece"> <tbody> <tr bgcolor="#99cccc"> <?php foreach( $myfinal $key => $value ) { if( is_array($value) ) { echo '<th colspan="'.sizeof($value).'">'.$key.'</th>'; } else { echo '<th colspan="0">'.$key.'</th>'; } } ?> </tr> </tbody> </table>
works 2 layers... arbitrary layers possible much more complex.
// top row echo '<tr>'; foreach( $myfinal $key => $value ) { if( is_array($value) ) { echo '<th colspan="'.sizeof($value).'">'.$key.'</th>'; } else { echo '<th colspan="1">'.$key.'</th>'; } } echo '</tr>'; //middle row echo '<tr>'; foreach( $myfinal $key => $value ) { if( is_array($value) ) { foreach($value $key => $column) { echo '<th colspan="1">'.$key.'</th>'; } } else { echo '<th colspan="1">no subcat</th>'; } } echo '</tr>'; //data echo '<tr>'; foreach( $myfinal $key => $value ) { if( is_array($value) ) { foreach($value $key => $column) { echo '<td>'.$column.'</td>'; } } else { echo '<td>'.$value.'</td>'; } } echo '</tr>';
php arrays table loops logic
Comments
Post a Comment