1

i would like to format it this way but i am unable to at the moment it looks like this:

    {"success":true,"user":"tom","gender":"male","age":"2"}
{"success":true,"user":"anna","gender":"female","age":"3"}

but it should look like this

  {
      "result":[ 
                 {"success":true,"user":"tom","gender":"male"},
                 {"success":true,"user":"anna","gender":"female"}
               ]
    }

this is my code

if ($result->num_rows > 0)
  {
    while($row = $result->fetch_assoc())
     {
       $user= $row["user"];
       $gender= $row["gender"];

       $response["user"] = $user;
       $response["gender"] = $gender;
       $response["success"] = true;

       echo json_encode($response); 

     }
   }
2
  • I fail to see how your examples and your code are related. Commented Jun 23, 2017 at 14:32
  • Question is fine as is, and makes perfect sense. Commented Jun 23, 2017 at 14:36

1 Answer 1

1
if ($result->num_rows > 0)
  {
    while($row = $result->fetch_assoc())
     {
       $user= $row["user"];
       $gender= $row["gender"];

       $response['result'][] = [
           'user' => $user,
           'gender' => $gender,
           'success' => true
       ];

     }
     echo json_encode($response);
   }

You were formatting it on each loop, which will output entirely separate sets of JSON.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much i have been stuck at this for hours really appreciate your answer :) :)
If my answer solved your problem, then please mark it as such by checking the tick below the voting buttons when it becomes available.

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.