I want to get json with php encode function like the following
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);
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);
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);
Just change that lines
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
To these
echo ",";
echo json_encode(array('id'=>$i, 'name' => $row['name']));
Here is a solution that 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 the json into an array and then implode it with glue (,) outputing the following {"results":[{"id":1,"name":"maadi"},{"id":2,"name":"monofiya"}]}
without the need to do the array first then pass it to the json_encode() function