while循环在一个数组中

时间:2016-04-18 15:39:59

标签: php mysql

$query = mysql_query("SELECT * FROM tableName WHERE status='confirm' ORDER BY datetime DESC ");
$invoice = mysql_fetch_assoc($query);

如何回应mysql获取数据,如下所示:

$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
array("firstname" => "James", "lastname" => "Brown", "age" => 31),
array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
);

1 个答案:

答案 0 :(得分:0)

您需要遍历结果并将值添加到数据数组中:

$query = mysql_query("SELECT * FROM tableName WHERE status='confirm' ORDER BY datetime DESC ");
$data = array();
while ($invoice = mysql_fetch_assoc($query)) {
  $data[] = array(
    'firstname' => $invoice['firstname'],
    'lastname' => $invoice['lastname'],
    'age' => $invoice['age'],
  );
}

mysql_fetch_assoc($query)只返回一行,因此只要它返回结果行(while),循环就会运行并将值添加到$data数组。