在PHP中按ID分组html表数据

时间:2014-01-25 20:11:29

标签: php html

我有这个代码

$result = mysql_query("select * tblsubject");
while(mysql_fetch_query($result)){
if($row['semester']=='1st'){
echo'<tr>
<td colspan="3">First Semester</td>
</tr>';
echo'<tr>';
echo'<td>'.$row['year'].'</td>';
echo'<td>'.$row['semester'].'</td>';
echo'<td>'.$row['subject'].'</td>';
echo'</tr>';
}
else{
echo'<tr>
<td colspan="3">Second Semester</td>
</tr>';
echo'<tr>';
echo'<td>'.$row['year'].'</td>';
echo'<td>'.$row['semester'].'</td>';
echo'<td>'.$row['subject'].'</td>';
echo'</tr>';
}

我总是这样输出。

|Year | Semester | Subject |
|     First Semester       |
|1stYr|    1st   | english |
|     First Semester       |
|1stYr|    1st   |  math   |
|     Second Semester      |
|1stYr|    2nd   | english |
|     Second Semester      |
|1stYr|    2nd   | science |

输出必须是这样的。他们将按学期分组。

|Year | Semester | Subject |
|     First Semester       |
|1stYr|    1st   | english |
|1stYr|    1st   |  math   |
|     Second Semester      |
|1stYr|    2nd   | english |
|1stYr|    2nd   | science |
谁能帮帮我?我真的无法解决它。我是php编程的新手。谢谢:))

1 个答案:

答案 0 :(得分:0)

首先,您应该按semester字段命令查询结果:

$result = mysql_query("select * tblsubject order by `semester` asc");
$cur_semester = '';
while ($row = mysql_fetch_array($result)){ 
    if ($cur_semester !== $row['semester']) {
        echo'<tr>
        <td colspan="3">' . $row['semester'] . ' Semester</td>
        </tr>';
        $cur_semester = $row['semester'];
    }

    echo'<tr>';
    echo'<td>'.$row['year'].'</td>';
    echo'<td>'.$row['semester'].'</td>';
    echo'<td>'.$row['subject'].'</td>';
    echo'</tr>';
}