2

我的阵列 -

$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>
4

1 回答 1

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>';
于 2013-02-21T20:51:02.163 回答