将MySQL查询数据格式化为自定义数组

时间:2010-01-27 19:39:45

标签: php mysql arrays

我从数据库查询中返回以下数据:

+---------------+-----------+------------------+--------------+-------+
| 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 个答案:

答案 0 :(得分: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...
}

我希望这会有所帮助。

答案 1 :(得分:0)

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

虽然我不支持你设置数据库的方式,但我不打算给你讲讲。我认为这是一个学校项目或其他什么。