我想使用以JSON格式返回的mysql数据创建吧。
[
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
]
我想创建类似this图表
但问题是这是从Table格式化的。但是我有如上所示的JSON数据。
以下是我关注的链接。我们可以转换格式的JSON数据,以便它可以根据显示的数据填充图表
https://blueflame-software.com/bar-chart-with-data-from-mysql-using-highcharts/
答案 0 :(得分:0)
您可以在Javascript中处理JSON以构建图表所需的数据,如下所示:
var jsonFromServer = [
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
];
以上是来自变量
中捕获的服务器的数据以下代码可帮助您从JSON响应中提取Y轴值(即唯一主题名称):
function getSubjects(){
var subjectsMap = {};
$.each(jsonFromServer, function(index, value){
if(!subjectsMap[value['Subject Name']]){
subjectsMap[value['Subject Name']] = 1;
}
});
return $.map(subjectsMap, function(index, val){ return val; });
}
然后我们需要为不同主题的每位教练提取得分,其形式应为:[{name:“Trainer”,data:[]}]其中数据是主题中得分应该相同的得分数组作为出现在Y轴数据中的主题的顺序。使用以下代码可以实现:
function getTrainers(){
var trainersMap = {};
$.each(jsonFromServer, function(index, value){
if(!trainersMap[value['Trainer']]){
trainersMap[value['Trainer']] = 1;
}
});
return $.map(trainersMap, function(index, val){ return val; });
}
function getMarks(){
var subjects = getSubjects();
var trainers= getTrainers();
var marks = {};
//initialize the trainers scores in all subjects to 0
$.each(trainers, function(index, trainer){
if ( !marks[trainer]){
marks[trainer] = {};
}
$.each(subjects, function(idx2, sub){
marks[trainer][sub] = 0;
});
});
//now populate with the actual values obtained from server
$.each(subjects, function(idx2, sub){
$.each(jsonFromServer, function(index, value){
var trainer = value['Trainer'];
var subName = value['Subject Name'];
var score = value['Score'];
if ( sub == subName){
marks[trainer][sub] = score;
}
});
});
//now format the marks object into the format required for highcharts
//i.e an array of object with properties [{name: "", data:[]}]
return $.map(marks, function(val, index){
var scoreArray = [];
$.each(val, function(index, score){
scoreArray.push(parseInt(score));
});
return {"name": index, "data": scoreArray};
});
}
可以在小提琴here中找到工作代码。