I am trying to make a json list to be used for a practice app I am busy with. It is supposed to look like this
{
"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"]
}
and this is the code I am currently using
<?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. ']';
?>
However I get this...whereby the individual arrays are not seperated by comma's
[
{ "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" ]
}
]
my question is how would you go about adding a comma to seperate each json object in this instance.Thanks
The only thing you actually json_encode()
is single book arrays. Because you simply paste all these pieces of JSON
behind each other, nothing adds the comma for you.
In stead of adding comma's manually, you should put all the books in an array and json_encode()
the entire books array.
This makes sure you have correct JSON
in the entire output.
Example
$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);