Reputation: 59
My android developer require JSON response like below.
[
{ "StudentId":"1", "StudentName":"Rahul", "StudentMarks":"83" }, { "StudentId":"2", "StudentName":"Rohit", "StudentMarks":"91"} ]
My current code for generate JSON API is like below.
<?php
$response = array();
require 'db.php';
$query = "SELECT * FROM news order by id desc";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) > 0) {
$response["news"] = array();
while ($row = $result->fetch_assoc()) {
$news= array();
$news["id"] = $row["id"];
$news["title"] = $row["title"];
$news["description"] = $row["description"];
array_push($response["news"], $news);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
I am getting response like below
{"news":[{"id":"1","title":"My first news title here","description":"My first news description will be here"}],"success":1}
I have tried lot of changes but not getting proper result like above. I want remove "news" and "success" from my response for make it as required response. What should I change for get response like first located code ?
Thanks
Upvotes: 1
Views: 55
Reputation: 460
Try this code
<?php
$response = array();
require 'db.php';
$query = "SELECT * FROM news order by id desc";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) > 0) {
$response["news"] = array();
while ($row = $result->fetch_assoc()) {
$arr[]=array('StudentId'=>$row["id"],'title'=>$row["title"],'description'=>$row["description"])
}
$response =$arr ;
// echoing JSON response
echo json_encode($response);
} else {
$response = array('success'=>0);
echo json_encode($response);
}
Upvotes: 1