有没有办法让PHP将sql结果直接转换为JSON?

时间:2012-05-24 21:37:38

标签: php mysql json

我很好奇我是否必须自己滚动,或者是否有一个我正在忽略的预先制作的PHP SQL库,我可以传入一个sql select查询并让它给我一个JSON对象(或者字符串)作为结果。

在伪代码中,我想要的是:

$startIndex = 0;
$myJSON = magicSqlToJSON("select first_name, last_name, phone,  (select count(id) from users) as total from users limit $startIndex, 2");

$ myJSON现在是:

{"users":[
   {"first_name":"Peter", "last_name":"O'Tool","phone":"1234567890","total":"100"},
   {"first_name":"Gary", "last_name":"Shandling","phone":"1234567890","total":"100"}
]}

我知道自己写这篇文章不会花很长时间,但我有点认为这种情况太普遍了,而且还不存在。

4 个答案:

答案 0 :(得分:2)

PHP中没有单个函数本身存在

但是,您可以使用mysqli_fetch_array()(例如)和json_encode()的组合快速完成此操作。您可能需要稍微调整父格式(即“用户”下面)

答案 1 :(得分:2)

PHP

为此目的,PHP具有json_encode()json_decode()功能,但您需要使用foreach或类似功能手动循环数据。

的MySQL

您可以使用lib_mysqludf_json之类的用户定义函数,它允许您从查询中返回JSON数组,如下所示:

select json_array(
           customer_id
       ,   first_name
       ,   last_name
       ,   last_update
       ) as customer
from   customer 
where  customer_id =1;

产生这个结果:

+------------------------------------------+
| customer                                 |
+------------------------------------------+
| [1,"MARY","SMITH","2006-02-15 04:57:20"] |
+------------------------------------------+

UDF中还有一个json_object函数,它可以让您在问题中非常接近地表示样本。

答案 2 :(得分:1)

没有直接功能但你可以做其他事情:

结果来自一个数组,所以只需调用

json_encode(数组); - > http://php.net/manual/en/function.json-encode.php

在它上面就是这样

示例:

$query = "select first_name, last_name, phone,  (select count(id) from users) as total from users limit $startIndex, 2";
$result = mysql_query($query) or die(mysql_error());

echo json_encode(mysql_fetch_array($result));

答案 3 :(得分:0)

我假设您使用PDO

echo json_encode($pdo->exec($sql)->fetchAll());

否则,一般模式是

$handle = execute_query($sql);
$rows = array();
while ($row = get_row_assoc($handle)) {
    $rows[] = $row;
}
echo json_encode($rows);