【问题标题】:Is there a way to have PHP convert sql results straight to JSON?有没有办法让 PHP 将 sql 结果直接转换为 JSON?
【发布时间】:2012-05-24 21:37:37
【问题描述】:

我很好奇我是否必须自己动手,或者是否有一个我忽略的预制 PHP SQL 库,我可以通过它传入一个 sql 选择查询并让它返回一个 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"}
]}

我知道自己写这篇文章不会花很长时间,但我有点认为这是一种太常见的需求,以至于它已经不存在了。

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    PHP 中没有原生的单个函数

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

    【讨论】:

      【解决方案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 函数,它应该可以非常接近地表示您的问题中的示例。

      【讨论】:

      • 这很酷,但其他答案似乎更接近我正在寻找的内容
      【解决方案3】:

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

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

      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));
      

      【讨论】:

      • 修正对不起我有点累了:)
      【解决方案4】:

      假设您使用 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);
      

      【讨论】:

        猜你喜欢
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多