2013-04-17 59 views
0

我想用融合图表创建图表之前使用JSON作为数据格式更改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" } 
    ] 
} 
+0

因为'$ Proses2'是一个对象(stdClass的),你可以轻松地添加新的特性,比如'chart'和'data',用'items'填补他们终于卸下'项目'物业 – MatRt

+0

@MatRt你能帮我举个例子吗? –

回答

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 Fiddle Demo

2

作为$Proses2是一个基本的对象(stdClass),你可以轻松地添加新的属性,如chartdata,你想要什么(在这种情况下,数据填充它们从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); 
+0

谢谢@MatRt,我会尽力的 –