1

我正在使用 PHP,我需要一种将整个记录集转换为 JSON 字符串的方法。

在搜索 Stack Overflow 时,我发现这个解决方案有效:

function recordSetToJson($mysql_result) {
  $rs = array();
  while($rs[] = mysql_fetch_assoc($mysql_result)) {
    // you don´t really need to do anything here.
  }
  return json_encode($rs);
}

这段代码的问题是我发现该函数mysql_fetch_assoc()在 PHP 5.5.0 中已被弃用。另一件事是我使用 PDO 连接到我的数据库。

鉴于上述情况,将 PDO 记录集转换为 JSON 的最佳解决方案是什么?我希望它也可以在更高版本的 PHP 中工作。

4

2 回答 2

15

解决方案很简单。考虑到变量$stmt是您的 PDO 记录集,您可以像这样将其转换为 JSON:

json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

有关这段代码中使用的函数的更多信息:

http://www.php.net/manual/en/function.json-encode.php

http://www.php.net/manual/en/pdostatement.fetchall.php

于 2013-03-08T07:01:17.650 回答
-1

你应该使用类似的东西

以前的某个地方

$stmt = $pdo->prepare("SELECT * FROM fruit WHERE name = ?");
$stmt->execute(array("Apple"));
....


function recordSetToJson($stmt) {
  $json_result = array();
  while($tmp = $stmt->fetch() ) {
       $json_result[] = $tmp;
  }
  return json_encode($json_result);
}

但最终的解决方案将完全取决于太多的因素。

于 2013-03-08T06:28:36.457 回答