Encode json using php?

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

+6
source share
5 answers

If I were you, I would not json_encode each individual array, but join the arrays together, and then json_encode combined array at the end. The following is an example of using short arrays syntax 5.4 :

 $out = []; while(...) { $out[] = [ 'id' => $i, 'name' => $row['name'] ]; } echo json_encode($out); 
+12
source

Do json_encoding as a LAST step. Create your data structure exclusively in PHP, and then encode that structure at the end. Performing intermediate encodings means that you basically create your own json string, which will always be complex and most likely β€œbroken”.

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

first collect everything into an array, and then encode everything in one go:

 $outputdata = array(); while($row = mysql_fetch_array($result)) { $outputdata[] = $row; } echo json_encode($outputdata); 
+1
source

Here is the solution I came with

  $i = 1; $array = array(); while($row = mysql_fetch_array($result)) { $array[] = json_encode(array('id'=>$i, 'name' => $row['name'])); $i++; } echo implode(',', $array); // Take output array glue it with the 

This will put json in an array and then untie it with glue (,), outputting the following {"results":[{"id":1,"name":"maadi"},{"id":2,"name":"monofiya"}]} without having to first an array and then pass it to json_encode ()

+1
source

Just change these lines

 echo json_encode(array('id'=>$i, 'name' => $row['name'])); echo ","; 

To these

 echo ","; echo json_encode(array('id'=>$i, 'name' => $row['name'])); 
-1
source

Source: https://habr.com/ru/post/897916/


All Articles