2016-08-12 65 views
-1

我需要你的幫助。也許這完全符合邏輯。所以,我的情況是:從PHP中的連接表mySql中垂直和水平地響應數據

我有MySQL表,它們分別是:

記錄表

_______________________________________ 
Student ID | Question ID | Answer 
_______________________________________ 
    1  |  1  | A 
    2  |  1  | C 
    3  |  1  | E 
    1  |  2  | D 
    2  |  2  | B 
    3  |  2  | A 
    ....... | .......... | ........ 
_______________________________________ 

和學生表:

_________________________________ 
Student ID | Student Name 
_________________________________ 
     1  |  Ronaldo 
     2  |  Messi 
     3  |  Neymar 
    .......... | ............. 
_________________________________ 

而且我想在我的報告呼應他們帶有如下表格的頁面:

_________________________________________________ 
Student |   Question and Answer 
      |____________________________________ 
      | 1 | 2 | 3 | ... | ... | ... | ... | 
_________________________________________________ 
Ronaldo | A | D | ........................... 
Messi  | C | B | ........................... 
Neymar  | E | A | ........................... 
........ | ................................... 
_________________________________________________ 

我使用PHP,所以我重複使用foreach(){}函數。但是如何在一次查詢中垂直和水平地回顯數據?

對不起我的PHP知識和邏輯。感謝您的關注。

+3

我沒有解決方案,但我會說這是你絕對想要在PHP中處理而不是在MySQL中處理的。 –

+0

是的,也許你是對的... – Agung

回答

0

一個簡單的方法來做到這一點(但絕不是唯一的一個):

首先獲取你的用戶及其答案:

SELECT 
    s.id AS student_id, 
    s.name AS student_name, 
    q.question_id, 
    q.answer 
FROM 
    students AS s 
INNER JOIN 
    questions AS q 
ON 
    s.id = q.student_id; 

你應該得到這樣的行:

array(
    'student_id' => '1', 
    'student_name' => 'Ronaldo', 
    'question_id' => 1, 
    'answer' => 'A', 
) 

OR

array(
    'student_id' => '2', 
    'student_name' => 'Messi', 
    'question_id' => 1, 
    'answer' => 'C', 
), 

然後,您可以遍歷他們重新進行排列:

$data = array(); 
foreach($rows as $row){ 
    if(!isset($data[$row['student_id']])){ 
     $data[$row['student_id']] = array(
      'student_name' => $row['student_name'], 
      'questions' => array(), 
     ); 
    } 

    $data[$row['student_id']]['questions'][] => array(
     'question_id' => $row['question_id'], 
     'answer' => $row['answer'], 
    ); 
} 

,這將給你這個數組:

$data = array(
    '1' => array(
     'student_name' => 'Ronaldo', 
     'questions' => array(
      array(
       'question_id' => 1, 
       'answer' => 'A', 
      ), 
      array(
       'question_id' => 2, 
       'answer' => 'D', 
      ), 
     ), 
    ), 
    '2' => array(
     'student_name' => 'Messi', 
     'questions' => array(
      array(
       'question_id' => 1, 
       'answer' => 'C', 
      ), 
      array(
       'question_id' => 2, 
       'answer' => 'B', 
      ), 
     ), 
    ), 
); 

最後,遍歷數組最後顯示的數據你想要的方式:

foreach($data as $student){ 
    echo $student['student_name'] . ' : ' ; 

    foreach($student['questions'] as $question){ 
     echo 'Question ' . $question['question_id'] . ' : ' . $question['answer'] . "\n"; 
    } 
} 

您將需要做一些適應,以適應您的需要。