如何使用数据库值创建动态json列表/数组

时间:2015-09-03 15:12:05

标签: php arrays json dynamic

我正在尝试制作一个json列表,用于我忙的练习应用。    它应该看起来像这样

 {
    "title": "District 9",
    "image": "http://api.androidhive.info/json/movies/2.jpg",
    "rating": 8,
    "releaseYear": 2009,
    "genre": ["Action", "Sci-Fi", "Thriller"]
},<---comma is present here
{
    "title": "Transformers: Age of Extinction",
    "image": "http://api.androidhive.info/json/movies/3.jpg",
    "rating": 6.3,
    "releaseYear": 2014,
    "genre": ["Action", "Adventure", "Sci-Fi"]
}

这是我目前正在使用的代码

<?php
        require '../../scripts/connect.php';

        $y="";
        $book ="";
        if($result = $db->query("SELECT * FROM posts") or die ($db->error)){
      if($count = $result->num_rows) {
             while($row = $result->fetch_object()){


        $y .= json_encode(array(
            "title"=> $row->title,
            "image"=>"http://www.mywebsite.com/posts/img/" . $row->id. ".jpg",
            "rating"=> $row->rating,
            "releaseYear"=> $row->date_added,
            "genre"=> [$row->category, $row->subcategory]

    ), JSON_PRETTY_PRINT);


      }
    }
    }
    echo '[' .$y. ']';


    ?>

但是我得到了这个...其中各个数组不是用逗号

分隔的
[
{ "title": "This is a test",
 "image": "http:\/\/www.mywebsite.com\/posts\/img\/1.jpg",
 "rating": 8.7,
 "releaseYear": "2015-09-02 02:19:10",
 "genre": [ "genre", "genre" ]
 }<---no comma here is the problem
{ 
"title": "This is another test",
"image": "http:\/\/www.mywebsite.com\/posts\/img\/1.jpg", 
"rating": 7.7,
"releaseYear": "2015-09-03 02:19:10", 
"genre": [ "genre", "genre" ] 
}
]

我的问题是你如何在这个实例中添加一个逗号来分隔每个json对象。谢谢

1 个答案:

答案 0 :(得分:0)

你实际上json_encode()唯一的东西就是单书数组。因为您只是将JSON的所有这些部分粘贴在一起,所以没有任何内容为您添加逗号。

您不应手动添加逗号,而应将所有图书放在一个数组中,并json_encode()整个图书数组。

这可确保您在整个输出中都有正确的JSON

示例

$books = []; // I renamed $y to $books, seems clearer.
$book = ""; // This doesn't do anything remove it.
if($result = $db->query("SELECT * FROM posts") or die ($db->error)){
    if($count = $result->num_rows) {
        while($row = $result->fetch_object()){
        $books[] = [
                "title"       => $row->title,
                "image"       =>"http://www.mywebsite.com/posts/img/" . $row->id. ".jpg",
                "rating"      => $row->rating,
                "releaseYear" => $row->date_added,
                "genre"       => [$row->category, $row->subcategory]
            ];
        }
    }
}
echo json_encode($books, JSON_PRETTY_PRINT);