Json 编码整个 mysql 结果集
我想使用 php 编码函数获取 json,如下所示
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
我希望输出 json 类似
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
,但输出 json 如下所示
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
当您意识到末尾有逗号时,我想删除它,以便它可以正确的 json 语法,如果我删除 echo ",";
当有多个结果时,json 将像这样生成{"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]}
并且该语法错误也
希望每个人都明白我的意思,任何想法将不胜感激
I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ",";
when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]}
and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我是你,我不会
json_encode
每个单独的数组,而是将数组合并在一起,然后在最后json_encode
合并的数组。下面是使用 5.4 的 短数组语法的示例:If I were you, I would not
json_encode
each individual array, but merge the arrays together and thenjson_encode
the merged array at the end. Below is an example using 5.4's short array syntax:将 json_encoding 作为最后一步进行。纯粹用 PHP 构建数据结构,然后最后对该结构进行编码。进行中间编码意味着您基本上是在构建自己的 json 字符串,这总是很棘手并且很可能“损坏”。
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
首先将其全部构建到一个数组中,然后一次性对整个内容进行编码:
build it all into an array first, then encode the whole thing in one go: