我刚用chartjs开始冒险。我试图修改我发现的所有教程以满足我的需要,但遗憾的是页面没有显示图表并且没有给出任何错误。任何人都可以提出建议。
$result='';
$sql="SELECT Q1.uUserName AS Technician, sum(if(Q2.dCatFK=1,1,0)) AS AM, sum(if(Q2.dCatFK=2,1,0)) as PM
FROM T_users as Q1 LEFT JOIN (SELECT dUser2FK, dCatFK FROM T_Defects
INNER JOIN T_settings WHERE (dDateClosed >= FYDateFROM AND dDateClosed <= FYDateTO)";
if (!empty($_SESSION['dept'])) { $sql .= ' AND dDeptFK = '.$_SESSION['dept'];}
if (!empty($_SESSION['area'])) { $sql .= ' AND dAreaFK = '.$_SESSION['area'];}
if (!empty($_SESSION['month'])){ $sql .= ' AND MONTH(dDateClosed) = '.$_SESSION['month'];}
$sql .=") as Q2 ON Q1.uPK = Q2.dUser2FK GROUP BY Q1.uUserName ORDER BY sum(if(dCatFK is not null,1,0)) DESC, Q1.uUsername;";
try{
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$label = array();
$data = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$data[] = $row["AM"];
$data[] = $row['PM'];
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
<canvas id="myChart_Fixed" width="1000" height="400"></canvas>
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var ctx = document.getElementById("myChart_Fixed");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
答案 0 :(得分:1)
您使用AM和PM数据附加$数据,因此没有2个数据集,而只有一个数据集。因为$ data [1]不存在。声明另外2个数组并分别插入AM和PM的数据,然后在$ data [0]处插入$ dataAM ...让代码说明一切:
... PHP文件
$data = array();
$dataAM = array();
$dataPM = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$dataAM[] = $row["AM"];
$dataPM[] .=$row['PM'];
}
$data[0] = $dataAM;
$data[1] = $dataPM;
... HTML文件
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},
答案 1 :(得分:0)
错字错误,改变了这个:
json_encode(array_values($数据[0]))
到此:
json_encode(array_values($数据))