解析高阶图的json响应

时间:2013-09-17 08:20:14

标签: php parsing highcharts json

我需要你们帮助。我试图将json响应解析为highcharts可以渲染成柱形图的东西。我搜索和搜索没有任何运气。

这是在渲染图表之前json数据应如何显示的示例:

[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]

这就是我的json响应的样子:

{"col":["name","tot"],"grp":{"wkd":[["","0"],["id-1","0"],["id-2","0"],["id-3","0"],["id-4","0"],["id-5","0"],["id-6","0"],["id-7","0"]]},"Spec":{}}

我需要的唯一信息是id-1到7及其值。

我使用curl发送一个带有令牌和秘密的URL的发布请求。

这是代码的卷曲部分和json_decode:

$ch = curl_init($signedUrl);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json',
                                           'Accept-language: en-GB',
                                           'Content-type: application/json',                                                                                
                                           'Content-length: ' . strlen($data_string))); 

$json = curl_exec($ch);

print "RESPONSE BODY (as string (JSON)):<br/><br/>" . $json;
echo "<br><br>";

$data = json_decode($json, true);

curl_close($ch);

我不知道如何在json_decode之后解析信息。我已经尝试了多个foreach字符串而没有任何运气。 有人可以帮我这个吗?

此致 菲利普

1 个答案:

答案 0 :(得分:1)

你想要打破对象的相关部分,循环,如果填充了id,将其作为数据抓取。然后你需要重新json_encode它在图表中使用:

$json       = '{"col":["name","tot"],"grp":{"wkd":[["","0"],["id-1","0"],["id-2","0"],["id-3","0"],["id-4","0"],["id-5","0"],["id-6","0"],["id-7","0"]]},"Spec":{}}';
$decoded    = json_decode($json);
$values     = $decoded->grp->wkd;

$i = 0;
foreach($values as $k=>$arr) {
    $id = $arr[0];
    if(!empty($id)) {
        $data[$i][]     = $i;
        $data[$i][]     = $arr[1];
        $cats[$i]       = $id;
        $i++;
    }
}
$data = json_encode($data);
$cats = json_encode($cats);

如果需要,还包括构建类别数组的部分。如果没有,只需省略。

此例程的输出是:

$ data:

[[0,"0"],[1,"0"],[2,"0"],[3,"0"],[4,"0"],[5,"0"],[6,"0"]] 

$ cats:

["id-1","id-2","id-3","id-4","id-5","id-6","id-7"]