水平显示垂直列数据

时间:2016-05-19 14:12:11

标签: php html mysql

我有一个数据库表,其中存储了学生的名字,姓氏和测试结果。对于每个学生,有多个测试,如

First-Name Last-Name Test Result
Fahad      Uddin     Merit
Safwan     Shah      Fail
Fahad      Uddin     Fail
Safwan     Shah      Merit

在上面的MySQL表中,Fahad Uddin和Safwan Shah的两个测试结果被保存在数据库中。

客户希望在屏幕上显示结果,如下所示,

First-Name Last-Name Test-1  Test-2 
Fahad      Uddin     Merit   Fail
Safwan     Shah      Fail    Merit

我被困在如何逐行显示测试结果。

 <table align="center">
                                                    <!--Main work here-->
                        <h1 class="text-center">Progress Report</h1>
                        <table>
                        <tr>
                        <th>First Name</th>
                        <th>Last Name</th>

                        <th>Grade</th>
                        </tr>
                  <?php
                        $query_year  = "SELECT t1.Pupils_FirstName,t1.Pupils_Surname, t2.Progress_Report_Grades_Code
                        from pupils t1 join (SELECT * FROM progress_track JOIN `time_table` ON time_table.Time_Table_ID = progress_track.Progress_Report_Time_Table_ID WHERE `Time_Table_Centre` LIKE '15' AND `Time_Table_Year` LIKE 'year10' AND `Time_Table_Subject` LIKE '10') t2 on t1.Pupils_ID = t2.Progress_Report_Pupils_ID";
                        $result_year = mysql_query($query_year);
                        while ($row_year = mysql_fetch_array($result_year)) {
                            $fname = $row_year['Pupils_FirstName'];
                            $sname = $row_year['Pupils_Surname'];
                            $grade = $row_year['Progress_Report_Grades_Code'];

                            echo "<tr><td>".$fname."</td>"."<td>".$sname."</td>"."<td>".$grade."</td></tr>";
                    ?>
                    <?php

                    }
                    ?>
                        </table> 

1 个答案:

答案 0 :(得分:0)

你可以改造数组并将两个记录合二为一,例如:

$data = array();
while ($row_year = mysql_fetch_array($result_year)) {
        $fname = $row_year['Pupils_FirstName'];
        $sname = $row_year['Pupils_Surname'];
        $grade = $row_year['Progress_Report_Grades_Code'];
        $full_name = "$fname $sname";
        if (isset($data[$full_name]))
            $data["$fname $sname"]["Progress_Report_Grades_Code_2"] = $grade;
        else
            $data["$fname $sname"] = $row_year;


}

foreach($data as $fullname=>$row){
        $fname = $row['Pupils_FirstName'];
        $sname = $row['Pupils_Surname'];
        $grade1 = $row['Progress_Report_Grades_Code'];
        $grade2 = $row['Progress_Report_Grades_Code_2'];
        echo "<tr><td>".$fname."</td>"."<td>".$sname."</td>"."<td>".$grade1."</td>"."<td>".$grade2."</td></tr>";
}