本文翻译自:JSON encode MySQL results
How do I use the json_encode()
function with MySQL query results? 如何在MySQL查询结果中使用json_encode()
函数? Do I need to iterate through the rows or can I just apply it to the entire results object? 我需要遍历行还是可以将其应用于整个结果对象?
#1楼
参考:https://stackoom.com/question/1bnb/JSON编码MySQL结果
#2楼
My simple fix to stop it putting speech marks around numeric values... 我的简单解决办法是停止在数字值周围添加语音标记...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
#3楼
One more option using FOR loop: 使用FOR循环的另一种选择:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
The only disadvantage is that loop for is slower then eg while or especially foreach 唯一的缺点是for的循环要慢于while或尤其是foreach
#4楼
Sorry, this is extremely long after the question, but: 抱歉,问题过了很久,但是:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
Just basically: 基本上就是:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
#5楼
$rows = json_decode($mysql_result,true);
就如此容易 :-)
#6楼
The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that. 根据我的经验,在您将数组中的根元素命名为某种东西之前,以上方法不起作用,在此之前,我无法访问最终json中的任何东西。
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick! 这应该够了吧!
Pär 派尔