PHP:无法编码多行的json [英] PHP: can't encode json with multiple rows
问题描述
在发布问题之前,我已经花了几个小时仔细研究了几个类似的答案.
I've spent a couple of hours looking through several the similar answers before posting my problem.
我正在从数据库中的表中检索数据,我想将其编码为JSON.但是,只有表具有一行时,json_encode()的输出才有效.如果有多个行,则 http://jsonlint.com/处的测试将返回错误.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
这是我的查询:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
这将为我提供以下JSON:
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
当我在 http://jsonlint.com/上运行测试时,它会返回以下错误:
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
但是,如果我仅使用JSON的前半部分...
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
...或者如果我仅测试下半部分...
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
...同一测试将返回有效JSON".
... the same test will return "Valid JSON".
我想要的是能够在表的每一行中以单个[有效] JSON输出.
What I want is to be able to output in one single [valid] JSON every row in the table.
任何建议将不胜感激.
推荐答案
问题是您要为每行吐出单独的JSON,而不是一次完成所有操作.
The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
我所做的较小更改是将数据库的每一行作为新值存储在$rows
数组中.这意味着完成后,您的$rows
数组将包含查询的所有所有行,因此一旦完成,您就可以获得正确的结果.
The minor change I've made is to store each row of the database as a new value in the $rows
array. This means that when it's done, your $rows
array contains all of the rows from your query, and thus you can get the correct result once it's finished.
解决方案的问题是,您正在为数据库的某一行回显有效的JSON,但是json_encode()
并不知道所有其他行,因此您将获得一系列单独的JSON对象,例如与包含一个数组的单个数组相对.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode()
doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.
这篇关于PHP:无法编码多行的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!