dongwei7245 2019-02-01 14:04
浏览 99

如何根据需要正确格式化sql json

Basically,I want to fetch data from mysql and format it into json like this:

[
  [
    "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"
  ],

]

I used this code:

<?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";
} 

But rather than what I wanted(mentioned above),i got this:

[["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"]]

It looks ok,but the major problem is that I don't want all the results compressed together ,I want it exactly the way mentioned..with line breaks(new lines) after every ..[,", and so on

Thanks

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换