2010-01-27 36 views
0

我已經被從我的數據庫查詢返回的以下數據:格式化MySQL查詢數據到自定義陣列

 
+---------------+-----------+------------------+--------------+-------+ 
| district_name | school_id | school_name  | section  | score | 
+---------------+-----------+------------------+--------------+-------+ 
| My ISD  |  11 | My First School | English  | 20 | 
| My ISD  |  11 | My First School | Math   | 23 | 
| My ISD  |  11 | My First School | Reading  | 24 | 
| My ISD  |  11 | My First School | Science  | 23 | 
| My ISD  |  12 | My Second School | English  | 11 | 
| My ISD  |  12 | My Second School | Math   | 19 | 
| My ISD  |  12 | My Second School | Reading  | 22 | 
| My ISD  |  12 | My Second School | Science  | 26 | 
+---------------+-----------+------------------+--------------+-------+ 

我需要把這個數據放到一個數組可以輕鬆地輸出由學校成績表:

 
School     English Math Reading Science 
------------------------------------------------------- 
My First School   20  23 24  23 
My Second School  11  19 22  26 

我在將這些數據格式化爲完成此操作的數組時遇到問題。理想的結構是:

array(
    $schoolName => array(
    'results' => array(
     'section' => $section_name 
     'score' => $score 
    ), 
), 
); 

我已經嘗試了幾種方法,但無法讓它們正常工作。

+2

你是什麼意思,你不能讓他們正常工作?出了什麼問題?有錯誤嗎?數據丟失了? – 2010-01-27 19:43:55

回答

0
while ($row = mysql_fetch_array($query)) { //you can define the query, right? 
    $array[$row['school_name']]['results'][$row['section']] = $row['score']; 
} 

雖然我不支持你設置數據庫的方式,但我不會給你一個講座。我會認爲這是一個學校項目或什麼的。

+0

上面的數據結構不是我的數據庫的結構。這是通過我的查詢返回的數據。 – imgrgry 2010-01-27 19:58:09

+1

不知道我的問題是什麼... ginormous大腦放屁...謝謝。 – imgrgry 2010-01-27 20:02:18

0
$table_rows = array(); 
while ($row = mysql_fetch_assoc($mysql_result)) { 
    $school_name = $row['school_name']; 
    $table_rows[$school_name]['results'][$row['section']] = $row['score']; 
    // adding the other stuff to $table_rows... 
} 

我希望這會有所幫助。