php - 使用php将大量mysql记录转换为json

标签 php mysql arrays json

我想使用 PHP 将大量 MySQL 数据转换为 JSON我有 20K 及以上的记录,但我无法将 MySQL 数据转换为 JSON。我想创建 REST API,因此需要以 JSON 格式发送(响应)数据。

我试过这个但没有得到输出:

代码:

$query = mysql_query("SELECT table1.field1, table1,field2, table1.field3, table2.field4 FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1");

$result = array();
while($row = mysql_fetch_assoc($query))
{   
    $result[] = array('Name' => $row["field1"], 'Last Name' => $row['field2'], 'country' => $row["field3"], 'location' => $row["field4"]);
}

echo json_encode($result);

最佳答案

除了你的查询错误,我假设这只是你问题中的输入错误,因为没有人将他们的列标记为 field1、field2 等。

您遇到的问题很可能是编码问题。尝试以下将结果编码为 UTF8,并有望产生有效的 JSON。

mysql_set_charset ("UTF8");
$query = mysql_query("SELECT table1.field1, table1field2, table1.field3, table2.field4 FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1");

$result = array();

while($row = mysql_fetch_assoc($query))
{

    $result[] = array('Name' => $row["field1"], 'Last Name' => $row['field2'], 'country' => $row["field3"], 'location' => $row["field4"]);
}

echo json_encode($result);

关于php - 使用php将大量mysql记录转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45342530/

相关文章:

php - mysqli 查询只返回第一行

mysql - mysql中从一张表导入到另一张表

c - 使用 malloc 给我的内存比预期的多吗?

java - 什么是同时存储 Integer 和 array[String] 值的良好数据结构?

php - 将用户重定向到登录页面,而不在 Facebook 页面上使用 fbml

php - 没有 http|https 的外部链接失败

php - 从 php 运行长 SAS 存储过程而无需挂起浏览器

Java:简单的 If 语句不执行

php - 使用Where和Group By子句在Yii中的CDBCriteria中编写查询

arrays - 类型末尾的双问号是什么意思?