循环多维数组像html表一样存在

时间:2011-07-10 20:26:28

标签: php multidimensional-array

$groups = array("Group1"=>array("V1"=>array(1,2,3,4,5),
                                "V2"=>array(2,3,4,5,6),
                                "V3"=>array(3,4,5,6,7)
                                ),
                "Group2"=>array("V1"=>array(11,22,33,44,55),
                                "V2"=>array(11,21,31,41,51),
                                "V3"=>array(12,23,34,45,56)
                                ),
                "Group3"=>array("V1"=>array(1,2,3,4,5),
                                "V2"=>array(1,2,3,4,5),
                                "V3"=>array(1,2,3,4,5)
                                ),
                "Group4"=>array("V1"=>array(1,2,3,4,5),
                                "V2"=>array(1,2,3,4,5),
                                "V3"=>array(1,2,3,4,5)
                                ),
                "Group5"=>array("V1"=>array(1,2,3,4,5),
                                "V2"=>array(1,2,3,4,5),
                                "V3"=>array(1,2,3,4,5)
                                )                
                );

我想从这个数组显示到html表这样的东西

     Group1          | Group2
     h1|h2|h3|h4|h5  | h1|h2|h3|h4|h5
V1   value of its       value of its
V2   value of its       value of its
V3

    Group3          |  Group4
    h1|h2|h3|h4|h5  |  h1|h2|h3|h4|h5
V1   value of its       value of its
V2   value of its       value of its
V3   value of its       value of its

    Group5          | 
    h1|h2|h3|h4|h5  | 
V1   value of its     
V2   value of its     
V3   value of its     

我想这样做:

 $g_list = array_keys($groups);
echo '<table border=1>';
for($g=0;$g<=sizeOf($groups);$g++){  
    if(($g+1)<sizeOf($groups)){
        echo "<tr>
                <td COLSPAN=6 ALIGN=center>".$g_list[$g]."</td>
                <td COLSPAN=6 ALIGN=center>".$g_list[$g+1]."</td></tr>";
        echo "<tr>
                <td>&nbsp</td><td>h1</td><td>h2</td><td>h3</td><td>h4</td><td>h5</td>
                <td>&nbsp</td><td>h1</td><td>h2</td><td>h3</td><td>h4</td><td>h5</td>
            </tr>";
         echo "<tr>
                <td>V</td>
                </tr>";
       //todo
    }
}

我找不到它?任何人都可以帮助我的PHP?

2 个答案:

答案 0 :(得分:1)

嵌套循环:

<?php
foreach ($groups as $group => $rows) {
      ....
        foreach ($group as $row_name => $row) {
           ?> <tr><td><?=$row_name ?></TD> <?
           foreach ($row as $value) {
              ?><td><?=$value?></TD><?
           }   
          ...
        }  
      ...
    }
?>

到disp 2使用计数var +使用模数(%)知道何时开始新行

答案 1 :(得分:1)

这里 - 不是很好,但有效:)

foreach($groups as $group_name=>$group){

    echo '<table>';
    echo '<tr>';
    echo '<td>h1</td><td>h2</td><td>h3</td><td>h4</td><td>h5</td>';

    foreach($group as $version=>$values){


        echo '<tr><td>'.$version.'</td>';
        foreach($values as $value){
            echo '<td>'.$value.'</td>';
        }
        echo '</tr>';
    }

    echo '</table>';
}