[英]Remove extra double quotes in generated JSON string from fetched DB results
我搜索了可能回答我問題的Google,但后來我陷入了沉思。
我的查詢中有一些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);
那是結果
["{"title":"Wedding","start":"2015-01-29 00:00:00"}","{"title":"Gathering","start":"2015-01-23 01:00:00"}"]
我只想刪除雙引號,並且輸出應如下所示:
[{"title":"Wedding","start":"2015-01-29 00:00:00"},{"title":"Gathering","start":"2015-01-23 01:00:00"}]
可能嗎?
預先感謝您的回答。
不,不要使用字符串操作(str_replace)
解決此問題。 JSON字符串構造不正確的原因是,您在循環內有多余/不需要的編碼。
剛完成創建數組結構,然后最終編碼:
$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.