简体   繁体   English

从获取的数据库结果中删除生成的JSON字符串中的多余双引号

[英]Remove extra double quotes in generated JSON string from fetched DB results

I have searched Google that might answer my question but then I came into a dead brain. 我搜索了可能回答我问题的Google,但后来我陷入了沉思。

I have some JSON output from my query 我的查询中有一些JSON输出

$myQuery = "SELECT title, start FROM reserved_b";
$result = $mysqli->query($myQuery) or die($mysqli->error);
$data = array();
while ( $row = $result->fetch_assoc() ){
   $data[] = json_encode($row);
}

$json = json_encode($data);
echo $str = str_replace('\\', '', $json);

then this is the result 那是结果

["{"title":"Wedding","start":"2015-01-29 00:00:00"}","{"title":"Gathering","start":"2015-01-23 01:00:00"}"]

I just want to remove the double quotes, and the output should be like this: 我只想删除双引号,并且输出应如下所示:

[{"title":"Wedding","start":"2015-01-29 00:00:00"},{"title":"Gathering","start":"2015-01-23 01:00:00"}]

Is it possible? 可能吗?

Thank you in advance for your answers. 预先感谢您的回答。

No, don't use string operations (str_replace) to solve this problem. 不,不要使用字符串操作(str_replace)解决此问题。 The reason why your JSON string is not well constructed is because you have a superfluous/unneeded encoding while inside the loop. JSON字符串构造不正确的原因是,您在循环内有多余/不需要的编码。

Just finish creating the array structure, then finally encode: 刚完成创建数组结构,然后最终编码:

$myQuery = "SELECT title, start FROM reserved_b";
$result = $mysqli->query($myQuery) or die($mysqli->error);
$data = array();
while ( $row = $result->fetch_assoc() ){
    $data[] = $row; // just push it as an array
}
// then finally, encode in the end
$json = json_encode($data);
echo $json;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM