转换行列JSON数据

时间:2015-02-16 10:16:18

标签: php json

我想创建一个谷歌图表,但我的json URL数据如下:

{"standings":[{"pos":1,"team":"TEAM A","score":"600","country":"vn"},{"pos":2,"team":"TEAM B","score":"500","country":"us"},{"pos":3,"team":"TEAM C","score":"500","country":"us"},{"pos":4,"team":"TEAM D","score":"200","country":"sg"},{"pos":5,"team":"TEAM E","score":0,"country":"us"}]}

我希望“得分”为行,“团队”为列。如何在PHP中制作它?我见过这个developers.google.com/chart/interactive/docs/php_example,但json数据是行和列,与我的json数据不同。

2 个答案:

答案 0 :(得分:0)

像这样使用json_decode()

   <?php $json_data = json_decode($data); ?>

现在,您可以使用json_data

答案 1 :(得分:0)

你需要解码现有的json字符串,并循环遍历它 像这样的东西 -

$json_str = '{"standings":[{"pos":1,"team":"TEAM A","score":"600","country":"vn"},{"pos":2,"team":"TEAM B","score":"500","country":"us"},{"pos":3,"team":"TEAM C","score":"500","country":"us"},{"pos":4,"team":"TEAM D","score":"200","country":"sg"},{"pos":5,"team":"TEAM E","score":0,"country":"us"}]}';
//Decode json
$list = json_decode($json_str,True);
//Loop through existing array and assign to res_list.
$res_list = Array("row" => Array(), "column" => Array());
foreach($list["standings"] as $li_contents){
    $res_list["column"][] = $li_contents["team"];
    $res_list["row"][] = $li_contents["score"];
}
//Encode array back to json.
$json_res = json_encode($res_list);
print_r($json_res);

/*
OUTPUT
{
    "row":["600","500","500","200",0],
    "column":["TEAM A","TEAM B","TEAM C","TEAM D","TEAM E"]
}
*/