php如何将MySQL数据捕获到多维数组中

时间:2012-09-09 09:21:56

标签: php mysql multidimensional-array

mysql_select_db($my_db, $con);
$result = mysql_query("SELECT * FROM word_test");
$i=1;

while($row = mysql_fetch_array($result))
{

  $a = array(
    $i => array(
      0 => $row['question'],
      1 => $row['op_1'],
      2 => $row['op_2'],
      3 => $row['op_3'],
      4 => $row['op_4'],
      6 => $row['ans']
    ),
  );
  $i=$i+1;

}//while loop ended     
print_r($a);

1 个答案:

答案 0 :(得分:2)

在循环的每次迭代中,你都会在$a中覆盖数组。在循环外拉出$a的定义,并使用array_push追加每一行:

$a = array();
while($row = mysql_fetch_array($result))
{
    $i => array(
        0 => $row['question'],
        1 => $row['op_1'],
        2 => $row['op_2'],
        3 => $row['op_3'],
        4 => $row['op_4'],
        6 => $row['ans']
    );
    array_push($a, $i);
    $i=$i+1;
}