我有一个数据集,它需要与 JavaScript 变量采用相同的格式,如下所示:
var theData = {
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
data: [65, 59, 90, 81, 56, 55, 40]
},
{
label: "My Second dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
data: [28, 48, 40, 19, 96, 27, 100]
}
],
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"]
};
数据是用 PHP 构建的,但我不能那样做。
这是我在 PHP 中的内容(示例数据,但填充方法相同):
$data = array();
$data['datasets'][1]['label'] = "First Data Set";
$data['datasets'][1]['borderColor'] = "rgba(30, 87, 153, .9)";
$data['datasets'][1]['backgroundColor'] = "rgba(30, 87, 153, .5)";
$data['datasets'][2]['label'] = "Afternoon";
$data['datasets'][2]['borderColor'] = "rgba(41, 137, 216, .9)";
$data['datasets'][2]['backgroundColor'] = "rgba(41, 137, 216, .5)";
// Loop through some foreachs and fill the $data
// Not the actual loop I use but same principle
foreach ($theData as $data)
{
$data['datasets'][1]['data'][] = data;
}
foreach ($otherData as $data)
{
$data['datasets'][2]['data'][] = data;
}
json_encode();
当我这样做时,这将返回给 JavaScript console.log(JSON.stringify(theData))
:
{
"datasets":{
"1":{
"label":"Morning",
"borderColor":"rgba(125, 185, 232, .9)",
"backgroundColor":"rgba(125, 185, 232, .5)",
"borderWidth":1,
"data":[
"24",
0,
0,
"30",
"24",
"36",
"36"
]
},
"2":{
"label":"Afternoon",
"borderColor":"rgba(41, 137, 216, .9)",
"backgroundColor":"rgba(41, 137, 216, .5)",
"borderWidth":1,
"data":[
"24",
0,
0,
"24",
"24",
"30",
"36"
]
}
},
"labels":[
"Sun Aug 14",
"Mon Aug 15",
"Tue Aug 16",
"Wed Aug 17",
"Thu Aug 18",
"Fri Aug 19",
"Sat Aug 20"
]
}
这适用于 Chart.js 2.3。顶部的示例数据直接来自 Chart.js 示例数据。上面的 JSON 是我的结果。因为它们不相同,所以图表不起作用。我可以更改我的 PHP 以使其更像顶部的示例吗?