6

I want to get json with php encode function like the following

<?php 
  require "../classes/database.php";

  $database = new database();
  header("content-type: application/json");
  $result = $database->get_by_name($_POST['q']);   //$_POST['searchValue']

  echo '{"results":[';
  if($result)
  {
     $i = 1;
     while($row = mysql_fetch_array($result))
     {
        if(count($row) > 1) 
        {
           echo json_encode(array('id'=>$i, 'name' => $row['name']));
           echo ",";
        }
        else 
        {
           echo json_encode(array('id'=>$i, 'name' => $row['name']));
        }
        $i++; 
     }
  }
  else
  {
     $value = "FALSE";
     echo json_encode(array('id'=>1, 'name' => ""));  // output the json code
  }

  echo "]}";

i want the output json to be something like that

{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}

but the output json is look like the following

{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}

As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too

Hope that everybody got what i mean here, any ideas would be appreciated

2
  • 1
    Do not produce JSON manually. Put all the data into a single data structure (an associative array, probably) and use json_encode() only once to produce the output out of this data structure. Commented Nov 10, 2021 at 13:27
  • 1
    Any answer below that advises anything other than using json_encode() at the end of your processing is giving you bad advice. In modern PHP, you'd just echo json_encode(['results' => $result->fetch_all(MYSQLI_ASSOC)]);. ...and your id values should probably be coming from you db too. Commented Nov 10, 2021 at 13:29

3 Answers 3

13

If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:

$out = [];
while(...) {
  $out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Sign up to request clarification or add additional context in comments.

2 Comments

Though not super important in your answer, $i will not increment in this snippet.
@mickmackusa Perhaps, but ... will not compile either, and there's no telling what that is a stand-in for, either.
9

Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".

$data = array();
while ($row = mysql_fetch_array($result)) {
   $data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);

1 Comment

Though not super important in your answer, $i will not increment in this snippet.
2

build it all into an array first, then encode the whole thing in one go:

$outputdata = array();
while($row = mysql_fetch_array($result)) {
    $outputdata[] = $row;
}

echo json_encode($outputdata);

1 Comment

Cleanest answer

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.