gpt4 book ai didi

javascript - 使用mysql数据创建条形图

转载 作者:行者123 更新时间:2023-11-29 21:04:54 25 4
gpt4 key购买 nike

我想使用以 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图表

但问题是它是从表中格式化的。但我有 JSON 数据,如上所示。

这是我正在关注的链接。我们能否将 JSON 数据转换为某种格式,以便它可以根据所示的数据填充图表

https://blueflame-software.com/bar-chart-with-data-from-mysql-using-highcharts/

最佳答案

您可以在 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: []}] 其中 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};
});

}

工作代码可以在 fiddle here中找到.

关于javascript - 使用mysql数据创建条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com