所以基本上我遇到了一个问题,我有一个以下面给出的格式的数组。我想使用这些数据创建一个highcharts折线图。
一切正常,只是因为我无法将此JSON转换为高级图表识别的JSON。
{
name: [
1000,
1001
],
data: [
{
January: "7",
February: "4",
March: "1",
April: "0",
May: "0",
June: "1",
July: "3",
August: "6",
September: "2",
October: "2",
November: "8",
December: "7"
},
{
January: "6",
February: "10",
March: "1",
April: "1",
May: "0",
June: "0",
July: "0",
August: "2",
September: "3",
October: "2",
November: "2",
December: "5"
}
]
}
Highcharts支持JSON
我想将此数组转换为如下结构:
[
{
name: '1000',
data: [7,4,1,0,0,1,3,6,2,2,8,7]
}, {
name: '1001',
data: [6,10,1,1,0,0,0,2,3,2, 2,5]
}
]
答案 0 :(得分:2)
使用foreach
遍历其中一个属性,并使用该元素和另一个属性中相应元素的值构建关联数组。
$result = array();
foreach ($input['name'] as $i => $name) {
$result[] = array('name' => $name, 'data' => array_map('intval', array_values($input['data'][$i])));
}
答案 1 :(得分:0)
<?php
$json_res = json_decode('{
"name": [
1000,
1001
],
"data": [
{
"January": "7",
"February": "4",
"March": "1",
"April": "0",
"May": "0",
"June": "1",
"July": "3",
"August": "6",
"September": "2",
"October": "2",
"November": "8",
"December": "7"
},
{
"January" :"6",
"February" :"10",
"March" :"1",
"April" :"1",
"May" :"0",
"June" :"0",
"July" :"0",
"August" :"2",
"September" :"3",
"October" :"2",
"November" :"2",
"December" :"5"
}
]
}',true);
$result = array();
foreach ($json_res['name'] as $key => $val) {
$result[] = array('name' => $val, 'data' => array_values($json_res['data'][$key]));
}
echo json_encode($result);exit;
#echo '<pre>'; print_r($result);
# answer the way you want
//[{"name":1000,"data":["7","4","1","0","0","1","3","6","2","2","8","7"]},{"name":1001,"data":["6","10","1","1","0","0","0","2","3","2","2","5"]}]
?>