- 此问题在此处已有答案**:
How to get a percentage of total when the query has a GROUP BY?(5个答案)
17小时前关门了。
我有一个饼图,它引用数组中的值。
我想把这些数组值显示为百分比。我该怎么做?
我用来生成此饼图的插件是chart.js
Javascript供参考:
success : function (data){
console.log(data);
var categoryname = ["Drain", "Building", "Pest", "Broken Utilities",
"Littering", "Leakage", "Lighting"];
var category = [];
var amount = [];
for (var i in data) {
category.push(categoryname[data[i].Category]);
amount.push (data[i].CaseNum);
}
var config = {
type: 'pie',
data: {
datasets: [{
data: amount,
backgroundColor: [
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)",
"rgba(59, 89, 152, 1)"
],
label: 'Dataset 1'
}],
labels: category
},
options: {
responsive: true
}
};
var ctx = $("#mycanvas");
var graph = new Chart(ctx, config);
}
Php供参考:
$query = "SELECT categoryID as 'Category', COUNT(Case.categoryID) as 'CaseNum'
FROM `Case` WHERE CaseTime BETWEEN DATE_SUB(now(), INTERVAL 6 MONTH) AND
now() GROUP BY categoryID ORDER BY categoryID";
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$conn->close();
print json_encode($data);
Piechart图像示例:
2条答案
按热度按时间nqwrtyyt1#
试试这个
我们的想法是先存储
data
对象中的Integers值,然后对总值求和,最后推送实际百分比值,并将%
添加到amount
数据中以生成饼图。x6yk4ghg2#
如果你有一个数字数组,那么它就像把数组减少到一个和,然后Map每个元素以除以这个和一样简单。
然后可以根据需要设置其格式。