php 如何使用 json_encode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10377570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use json_encode
提问by Anil
I'm dealing with highcharts with dynamic data (values retrieved from database). By writing a query i was able to retrieve the following data from the table
我正在处理带有动态数据(从数据库中检索的值)的 highcharts。通过编写查询,我能够从表中检索以下数据
Item 2011 2012
pen 5 7
pencil 4 20
eraser 6 43
I want to store the above info in the following structure and pass it to another page
我想将上述信息存储在以下结构中并将其传递到另一个页面
[{ name:'pen', data: [5,7]},{ name:'pencil', data: [4,20]},{ name:'eraser', data: [6,43]}]";
I want to push the above data to the drilldown highchart.
我想将上述数据推送到钻取高图。
Is there a way i can generate in this format? I've tried using json_encode but unable to succeed. Can i achieve this using json_encode?
有没有办法以这种格式生成?我尝试使用 json_encode 但无法成功。我可以使用 json_encode 来实现吗?
UpdatedI've tried in this way
更新我已经尝试过这种方式
while($row = mysql_fetch_assoc($result))
{
$rows[]= $row;
}
echo json_encode($rows);
and got
并得到
[{"Item":"pen","2011":"5","2012":"7"},{"Item":"pencil","2011":"4","2012":"20"},{"Item":"eraser","2011":"6","2012":"43"}]
回答by Logan Serman
json_encodeis a convenience method to convert an array into JSON format. To have the output you provided, you will need an array of arrays. Each sub-array has keys "name" and "data", where "name" is the Item column, and "data" is another array containing values from 2011 and 2012.
json_encode是一种将数组转换为 JSON 格式的便捷方法。要获得您提供的输出,您将需要一个数组数组。每个子数组都有键“name”和“data”,其中“name”是Item列,“data”是另一个包含2011年和2012年值的数组。
$results = mysql_query("...");
$arr = array();
while ($row = mysql_fetch_assoc($results))
{
$name = $row['Item'];
$data = array($row['2011'], $row['2012']);
$arr[] = array('name' => $name, 'data' => $data);
}
echo json_encode($arr);
回答by John Conde
- Loop through the database results and put the results in an array
- JSON encode the array
- 循环遍历数据库结果并将结果放入数组中
- JSON 编码数组

