0

我想使用融合图表创建图表并使用 json 作为数据格式

如果我之前的数据是这样的:

{
 "items": [
   {
      "2013-03-28": 1771,
      "2013-03-29": 1585,
      "2013-03-30": 1582,
      "2013-03-31": 1476
    }
  ]
}

我在处理中使用 php 获得上述数据:

<?php
$param  = $_GET['myparam'];

$Data = file_get_contents("http://mylink.com/proccess.php?output=json");

$Proses2 = json_decode($Data);

$array = array();
$array[] = (object)$Proses2;

if ($_GET['callback']) {
    echo $_GET['callback'] . '('.json_encode($array).')';
}else{
    echo '{"items":'. json_encode($array) .'}';
}

如何更改数据,使其变得像这样的图表中使用的格式?

{ 
   "chart": { 
        "caption" : "Weekly Sales Summary" ,
        "xAxisName" : "Week",
        "yAxisName" : "Sales",
        "numberPrefix" : "$"
},

"data" : 
   [
        { "label" : "Day 1", "value" : "14400" },
        { "label" : "Day 2", "value" : "19600" },
        { "label" : "Day 3", "value" : "24000" },
        { "label" : "Day 4", "value" : "15700" }
   ]
}

后来变成了:

{ 
   "chart": { 
        "caption" : "Weekly Sales Summary" ,
        "xAxisName" : "Week",
        "yAxisName" : "Sales",
        "numberPrefix" : "$"
},

"data" : 
   [
        { "label" : "2013-03-28", "value" : "1771" },
        { "label" : "2013-03-29", "value" : "1585" },
        { "label" : "2013-03-30", "value" : "1582" },
        { "label" : "2013-03-31", "value" : "1476" }
   ]
}
4

2 回答 2

2

作为$Proses2一个基本对象 ( stdClass),您可以轻松地添加新属性,如chartand data,用您想要的内容填充它们(在本例中,数据来自items),最后删除该items属性

这是一个例子:

<?php

// The json
$json = '{"items":[{"2013-03-28":1771,"2013-03-29":1585,"2013-03-30":1582,"2013-03-31":1476}]}';

// Extract the json to a STD class object
$object = json_decode($json);

// print the actual object
print_r($object);

// modify object by adding new property
$object->chart = array(
   "caption" =>"Weekly Sales Summary",
   "xAxisName" => "Week",
   "yAxisName" => "Sales",
   "numberPrefix" => "$"
);

// Remove previous property
unset($object->items);

print_r($object);
于 2013-04-17T04:33:35.270 回答
2
var item = { 
    "items":{
      "2013-03-28": "1771",
      "2013-03-29": "1585",
      "2013-03-30": "1582",
      "2013-03-31": "1476"
      }
    };

var data = [];temp=0;
for(var key in item.items)
{
alert(key);alert(item.items[key]);
data.push({});
data[temp].label = key;
data[temp].value = item.items[key];
temp++;
}
alert(JSON.stringify(data));

JS 小提琴演示

于 2013-04-17T04:52:08.350 回答