基本上,我想从mysql获取数据并将其格式化为json:
[
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
[
"title" => "first",
"uploader" => "root"
],
]
我使用了以下代码:
<?php
require 'config.php';
$query = $_GET['q'];
if ($query==null) {
exit('No query');
}
$sql = "SELECT title,uploader FROM `uploads_public` WHERE Title =:query ";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":query", $query, PDO::PARAM_STR);
// Attempt to execute the prepared statement
if($stmt->execute()){
echo "Your search $query has the following results(normal json):<br>";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json).'<br>';
echo "While it has the following results when replaced<br>";
echo str_replace('}',']',str_replace(':','=>',str_replace('{', '[', "$json")));
} else{
echo "Something went wrong. Please try again later. <br>"; print_r($stmt->errorInfo());
}
// Close statement
unset($stmt);
unset($pdo);
}
else{
echo "No input";
}
但不是我想要的东西(如上所述),我得到这个:
[[ “标题”=> “第一”, “上载”=> “根”],[ “标题”=> “第一”, “上载”=> “根”],[ “标题”=> “ first”,“ uploader” =>“ root”],[“ title” =>“ first”,“ uploader” =>“ root”],[“ title” =>“ first”,“ uploader” =>“根 “],[” 标题 “=>” 第一”, “上载”=> “根”],[ “标题”=> “第一”, “上载”=> “根”],[ “标题”=> “ first”,“ uploader” =>“ root”],[“ title” =>“ first”,“ uploader” =>“ root”]]
看起来还可以,但是主要的问题是我不希望将所有结果压缩在一起,我想要的就是上面提到的方法。.在每个.. [
之后加上换行符(新行), ",
等等
谢谢