使用while/foreach构建一个复杂的表


Build a complicated table with while/foreach

我试图从数组建立一个结果表。我目前有这样的输出结果:

   ID       VALUE             EXTRA
 --------------------------------------
|  1  |     Value 1         | Extra 1  |
|-----|---------------------|----------|
|  1  |     Value 2         | Extra 2  |
|-----|---------------------|----------|
|  2  |     Value 3         | Some 1   |
|-----|---------------------|----------|
|  3  |     Value 4         | Some 2   |
|-----|---------------------|----------|
|  3  |     Value 5         | Nothing  |
 --------------------------------------  

注意重复的ID值。我想做的是在当前循环中构建一个循环,它不会显示重复的id。像这样:

   ID       VALUE             EXTRA
 --------------------------------------
|  1  |     Value 1         | Extra 1  |
|     |---------------------|----------|
|     |     Value 2         | Extra 2  |
|-----|---------------------|----------|
|  2  |     Value 3         | Some 1   |
|-----|---------------------|----------|
|  3  |     Value 4         | Some 2   |
|     |---------------------|----------|
|     |     Value 5         | Nothing  |
 --------------------------------------  

下面是我当前的代码,简化如下:

<?php
$i=0;
while ($i < $mynum) {
$f1=mysql_result($myresult,$i,"tableID");
$f2=mysql_result($myresult,$i,"values");       
$f3=mysql_result($myresult,$i,"extra");
?>
<tr>
 <td><?php echo $f1; ?></td>
 <td><?php echo $f2; ?></td>
 <td><?php echo $f3; ?></td>
</tr>       
<?php
$i++;
}
?>

是否有办法以我想要的方式动态地构建这个表?或者我应该重新考虑我的策略吗?

假设ID按顺序排序,将ID存储在一个单独的变量中,并检查它是否发生了变化。如果有,打印ID;如果没有,则打印&nbsp;或类似的值。

这里有一种方法可以从您提供的代码中实现

<?php
    $i=0;
    $previousId = ''; // keeps track of the previous Id 
    while ($i < $mynum) {
    $html = '';
    $f1=mysql_result($myresult,$i,"tableID");
    $f2=mysql_result($myresult,$i,"values");       
    $f3=mysql_result($myresult,$i,"extra");
    $html .= '<tr>';
    if($previousId != $f1){ // fill the cell only if the new Id is different from the previous value
        $html .= '<td>'.$f1.'</td>';
    } else {
        $html .= '<td>&nbsp;</td>';
    }
            $previousId = $f1;
    $html .= '<td>'.$f2.'</td>';
    $html .= '<td>'.$f3.'</td>';
    $html .= '</tr>';
    $i++;
    }
            echo $html;
 ?>

但这是假设$f1是有序的