I want to get json with php encoding function as below.
<?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 json output to be something like this
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but json output is as follows
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you understand that there is a comma at the end, I want to remove it so that it can be the correct json syntax if I delete echo ",";
when there was more than one result that json would generate, like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]}
and this syntax is also incorrect
Hope everyone got what I mean here, any ideas will be appreciated
source share