根据查询将所有行提取到数组中 [英] Fetch all rows based on the query into an array
本文介绍了根据查询将所有行提取到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
我想做的是根据查询获取所有行并将其馈送到数组中,以提供如下输出:
What I would like to do is fetch all rows based on the query and feed those into the array, to give me an output like this:
["1", "", "", "", "", ""]
["2", "", "", "", "", ""]
etc...
我想我需要遍历行并建立数组,但我不知道如何.
I presume I need to loop through the rows and build up the array but I don't know how.
推荐答案
$result = mysql_query("SELECT * FROM $tableName");
$arr_json = array();
while ($row = mysql_fetch_assoc($result)) {
$json = json_encode($row);
$arr_json[] = $json;
}
看起来是j08691的答案,看来我可能误会了.
Looking a j08691's answer, it looks like I might have misunderstood.
无论如何,如果您不知道自己有多少列,请执行以下操作:
Anyway, if you don't know how many columns you have, do this:
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
这篇关于根据查询将所有行提取到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文