1

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

8
  • what about sucess response ? Commented Jan 14, 2017 at 9:07
  • @Rishi I have added response that I am getting. Commented Jan 14, 2017 at 9:08
  • why this [{{ ? is it [{ ? , I can see 3 opening and only 2 closing brackets Commented Jan 14, 2017 at 9:10
  • @Rishi Sorry...its by mistake of copy paste Commented Jan 14, 2017 at 9:11
  • 1
    ok, then you should pass news directly. echo json_encode($response['news]); Commented Jan 14, 2017 at 9:23

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.