2

I am having a small problem, I am showing json using PHP, I have this code:

foreach($result as $r){

        $returnEcho["Id"]       = $r["id"];
        $returnEcho["Username"] = $r["username"];
        $returnEcho["Email"]    = $r["email"];
        $returnEcho["Info"]     = $r["Info"];

        echo json_encode($returnEcho);

The problem with this code is, it will display the JSON like this:

{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}

But what I want is something like this:

[   
 {
  "Username":"X",
  "Email":"X",
  "Info":"X"
 },
 {
  "Username":"X",
  "Email":"X",
  "Info":"X"
 }
]

How can I do this? Thanks.

0

1 Answer 1

4

You have to build everything in an array and echo the json only after foreach finish. Like this:

 $return = [];
 foreach($result as $r){
    $returnEcho["Id"]       = $r["id"];
    $returnEcho["Username"] = $r["username"];
    $returnEcho["Email"]    = $r["email"];
    $returnEcho["Info"]     = $r["Info"];
    $return[] = $returnEcho;
 }
 echo json_encode($return);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That is what I was looking for.

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.