Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

encode json using php?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...