如何使用json_encode [英] how to use json_encode

查看:118
本文介绍了如何使用json_encode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理动态数据(从数据库中检索的值)的highcharts。
通过编写查询,我可以从表格中检索以下数据

 项目2011 2012 
笔5 7
铅笔4 20
橡皮擦6 43

我想存储上面的信息在下面的结构中传递给另一个页面

$ $ p $ $ $ $ $ $ $ $ [ 7]},{name:'pencil',data:[4,20]},{name:'eraser',data:[6,43]}];

我想将上面的数据推送到深入的高图。



有没有办法我可以生成这种格式?我试过使用json_encode但无法成功。
我可以使用json_encode来实现吗?



更新
我试过这种方式
$ b $ pre $ while($ row = mysql_fetch_assoc($ result))
{
$ rows [] = $ row;

}
echo json_encode($ rows);

并得到

  [{Item:pen 2011: 5, 2012: 7},{ 物品: 铅笔, 2011: 4, 2012: 20},{ 物品:橡皮擦,2011:6,2012:43}] 


解决方案 json_encode 是一种将数组转换为JSON格式的简便方法。要获得您提供的输出,您需要一个数组数组。每个子数组都有名称和数据键,其中名称是项目列,数据是包含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);


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

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?

Updated I'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"}]

解决方案

json_encode is 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.

$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);

这篇关于如何使用json_encode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆