动态表问题

时间:2012-11-28 06:58:15

标签: php mysql arrays

我正在尝试创建一个表,数据表示如下:

Skills   | Project #1 | Project #2 | Project #3
Skill #1    Grade         Grade        Grade
Skill #2    Grade         Grade        Grade

基本上,以Project开头的列是动态的,并通过SQL查询获取并存储在数组中。

技能也是动态的并存储在数组中。然后,每项技能的成绩应反映其所在项目的成绩。

所有这些数据都可在DB中找到。我可以在一个查询中获取技能,项目和成绩。

我正在试图弄清楚如何使这项工作。现在,我只能弄清楚如何获得展示的技能和项目。不过,我不知道如何让它们与合适的等级相匹配。这就是我所拥有的

         $sql = "select skills.name as skillName, projects.name, projects_assessments.assessment  from skills
              INNER JOIN projects_assessments
              ON skills.id = projects_assessments.skillID
              INNER JOIN projects
              ON projects_assessments.projectID = projects.id
              WHERE projects_assessments.studentID = '{student}'
              AND skills.teacher = '{teacher}'";
        $result = mysql_query($sql) or die (mysql_error());
        while($row=mysql_fetch_array($result)) {
            $projects[] = $row['name'];
            $skills[] = $row['skillName'];
        }
        echo "<table><tr><th>Skill</th>";
        $projects = array_unique($projects);
        foreach($projects as $project) {
            echo "<th>$project</th>";
        }
        echo "
        </tr>";
        foreach($skills as $skill) {
            echo "<tr><td>$skill</td></tr>";
        }
        echo "
        </table>

返回:

    Skills   | Project #1 | Project #2 | Project #3
   Skill #1                   
   Skill #2                  

基本上我现在需要的是匹配每种技能的等级。该数据存储在$ row ['assessment']中。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

只需在二维数组中构建表:

$table = array();
while ($row = mysql_fetch_array($result)) {
    $table[$row['skillName']][$row['name']] = $row['assessment'];
}

$firstRow = current($table);
// draw columns based on $firstRow

foreach ($table as $skillName => $projectList) {
    // start row
    foreach ($projectList as $assessment) {
        // start column with $assessment as value
    }
}

重要

确保正确排序行:

ORDER BY skillName, name;