Reputation: 26732
My array -
$myfinal = Array(
13 => Array
(
5 => 85,
4 => 75,
3 => 65,
2 => 55
),
12 => 11,
7 => 100
);
This is what I want to 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, I tried with the first tr and th but for the rest I am confused with the 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 as $key => $value )
{
if( is_array($value) )
{
echo '<th colspan="'.sizeof($value).'">'.$key.'</th>';
}
else
{
echo '<th colspan="0">'.$key.'</th>';
}
}
?>
</tr>
</tbody>
</table>
Upvotes: 2
Views: 3931
Reputation: 4157
Works for two layers... Arbitrary layers is probably possible but much more complex.
// Top row
echo '<tr>';
foreach( $myfinal as $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 as $key => $value )
{
if( is_array($value) )
{
foreach($value as $key => $column) {
echo '<th colspan="1">'.$key.'</th>';
}
}
else
{
echo '<th colspan="1">No subcat</th>';
}
}
echo '</tr>';
//Data
echo '<tr>';
foreach( $myfinal as $key => $value )
{
if( is_array($value) )
{
foreach($value as $key => $column) {
echo '<td>'.$column.'</td>';
}
}
else
{
echo '<td>'.$value.'</td>';
}
}
echo '</tr>';
Upvotes: 2