我的阵列 -
$myfinal = Array(
13 => Array
(
5 => 85,
4 => 75,
3 => 65,
2 => 55
),
12 => 11,
7 => 100
);
这是我想要动态生成的(表格) -
必需输出 - 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>
我的代码尝试,我尝试了第一个tr和th但是其余的我对循环感到困惑:
<?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>
答案 0 :(得分:2)
适用于两层......任意层可能是可能的,但更复杂。
// 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>';