2012-11-28 40 views
1

我試圖創建一個表,用數據來表示,像這樣:動態表格文檔

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

從本質上講,與項目開頭的列是動態的,並通過一個SQL查詢抓住並存儲在一個數組。

技能也是動態的,並存儲在數組中。然後每個技能的等級應反映其所在項目所收到的等級。

所有這些數據都可以在數據庫中找到。我可以在一個查詢中獲取技能,項目和成績。

我想弄清楚如何使這項工作。現在,我只能弄清楚如何讓技能和項目展現出來。不過,我不知道如何讓它們與適當的等級匹配。下面是我有

  $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']中。

感謝您的幫助!

+0

嘗試尋找在http:// stackoverflow.com/questions/7674786/mysql-pivot-table – scwagner

+0

我不太確定,因爲連接不是總結...他們是字符串。 –

+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;