如何从PHP发送JSON格式的对象数组 [英] How to send an array of objects in JSON format from PHP
问题描述
php的新手.我正在尝试将JSON数据以名称-值对的形式发送到前端.我尝试了一个此处的示例.以下是我的代码片段,以JSON名称值格式发送数据.
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);
我在前端找到了
Object {id: 12, name: "Manisha"}
问题是我期望有一组对象.上面的值是从SQL查询获得的最后一个值.我应该对这段代码进行哪些更改,以便获得对象数组.
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"}]
请咨询.
推荐答案
$ list必须是一个数组,您可以像下面的代码中那样将项目推入其中:
$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);
您还可以使用方法 fetch_all()来获取所有行一次,而不是循环遍历.尽管在此示例中,您将获得所选的所有字段,而不仅仅是ID和名称.
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);
这篇关于如何从PHP发送JSON格式的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!