Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an array of objects in JSON format from PHP

Tags:

json

php

New to php. I am trying to send JSON data to front end in name-value pair. I tried an example which I got here The following is my code fragment which sends the data in JSON name value format.

while($stmt->fetch()){
    $list = array('id' => $fid, 'name' => $fname);
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);

I got this on front-end

Object {id: 12, name: "Manisha"}

The problem is I was expecting an array of objects. The above value is the last value obtained from the SQL query. What are the alterations I should make to this code so that I can get an array of objects. Something like

[{"id":"1","name":"Kumari"}, {"id":"2","name":"KM"}, {"id":"3","name":"Manisha"}]

Please advice.

like image 278
Kumari Manisha Avatar asked Mar 25 '13 15:03

Kumari Manisha


1 Answers

$list needs to be an array, and you can just push items to it like in this code:

$list = array();
while($stmt->fetch()){
    $list[] = array('id' => $fid, 'name' => $fname);
}
$stmt->free_result();
$stmt->close();
echo json_encode($list);

You could also use the method fetch_all() to get all rows at once, instead of iterating with a loop. Although in this example you'd get all fields that you've selected, instead of just id and name.

$list = $stmt->fetch_all();
$stmt->free_result();
$stmt->close();
echo json_encode($list);
like image 80
Jose Armesto Avatar answered Oct 31 '22 11:10

Jose Armesto