MYSQL和PHP组按字段数据结果

时间:2011-08-07 17:49:10

标签: php arrays loops group-by mysqli

我正在尝试根据数据库中日志中的数据创建报告,如下所示:

id |学生|类型|标记
1 23494 CAT1 50
2 23495 CAT1 20
3 23494 CAT2 35
4 23495 MIDTERM 40

到目前为止,我的选择语句如下所示:

$res = @mysqli_query ($dbc, "SELECT id, student, type, GROUP_CONCAT(marks) AS mark, GROUP_CONCAT(type) AS types FROM log WHERE class = '1' AND term = '2' GROUP BY student DESC");

// Fetch and print all the records....<br>
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {

        echo '<tr>
            <td align="left">'. $row['student'] .'</td>';

        //$exams = split(",", $row['exams']); // 4,3,1,2
        $marks = split(",", $row['mark']); // 10,20,40,50

        foreach( $marks as $mark ) {
             echo '
                   <td align="left">' . $mark . '</td>
                ';
        }

        echo '</tr>';

} //End LOOP

//Then i end table

到目前为止,数据显示如下:

学生| CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40

问题是代码没有根据'type'排列'marks'(查看id4的MIDTERM输出和相应的显示)。

问题:

我如何按学生显示结果,然后在适当的单元格/组中显示标记,如下所示:?

学生| CAT1 | CAT2 | MIDTERM
23494 50 35
23495 20 40

感谢Advance Guys。

1 个答案:

答案 0 :(得分:1)

首先,尝试使逻辑远离布局。首先收集所需数据然后再显示它通常是一种好习惯。

使用GROUP_CONCAT可能会使事情变得更复杂,因为您不知道每个学生将获得多少结果,也无法轻松确定哪些标记属于哪种类型。

考虑到这一点,我已经创建了一个解决方案。当然,你仍然需要扩展查询。

$query = 'SELECT student, type, marks FROM log';
$res = mysqli_query($query);
$studentMarks = array();

while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
    $studentMarks[$row['student']][$row['type']] = $row['marks'];
}

// Now $studentMarks should look like:
// $studentMarks = array(
//    23494 => array('CAT1' => 50, 'CAT2' => 35)
//  , 23495 => array('CAT1' => 20, 'MIDTERM' => 40)
// );    

echo '<table><thead><tr>';
echo '<td>Student</td><td>CAT1</td><td>CAT2</td><td>MIDTERM</td>';
echo '</tr></thead><tbody>';

foreach($studentMarks as $studentId => $marks)
{
    echo '<tr>';
    echo '<td>', $studentId, '</td>';
    echo '<td>', (isset($marks['CAT1']) ? $marks['CAT1'] : '&nbsp;'), '</td>';
    echo '<td>', (isset($marks['CAT2']) ? $marks['CAT2'] : '&nbsp;'), '</td>';
    echo '<td>', (isset($marks['MIDTERM']) ? $marks['MIDTERM'] : '&nbsp;'), '</td>';
    echo '</tr>';
}
echo '</tbody></table>';