我有PHP脚本,该脚本可连接到mySQL数据库,该数据库进行查询并返回数据,然后将其循环遍历并添加到数组中。这是我的php脚本:
<?php
// Database credentials
$dbHost = 'localhost';
$dbUsername = 'demo';
$dbPassword = 'demo';
$dbName = 'syndicationdashboard';
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
// Create connection and select db
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Get data from database
$sql = "select Priority,Automated,isAutomatable,isNotAutomatable from automation_progress where platform = 'Cox' and update_date in (select MAX(update_date) FROM automation_progress) order by priority";
$data = array();
if ($result = mysqli_query( $db, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
$newData = array();
$firstLine = true;
foreach ($data as $dataRow)
{
if($firstLine)
{
$newData[] =array_keys($dataRow);
$firstLine = false;
}
$newData[] = array_values($dataRow);
}
#return $newData;
echo json_encode($newData);
mysqli_close($db);
?>
以下是此脚本的输出:
[["Priority","Automated","isAutomatable","isNotAutomatable"],["All","216","860","44"],["P1","213","567","34"],["P2","1","148","6"],["P3","2","136","3"],["P4","0","7","1"],["P5","0","2","0"]]
最后,我正在进行ajax调用,以从脚本中获取数据并将数据加载到Google图表中。
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://10.21.124.252:8080/automationBarDataCox.php",
success: function (jsonData) {
var data = google.visualization.arrayToDataTable(jsonData);
var options = {
chart: {
title: 'Automation Performance',
},
vAxes: {
0: {title: 'Automated'},
},
legend: { position: 'left'},
bars: 'vertical',
};
var chart = new google.charts.Bar(document.getElementById('cox_barchart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
});
}
</script>
加载图表时,由于数字返回为字符串而不是数字,因此返回的数据导致出现问题。有关如何解决此问题的任何想法?
答案 0 :(得分:2)
mysqli_fetch_assoc()
返回字符串的关联数组。如果要将值键入为整数,则必须做一些额外的工作:
if ($result = mysqli_query($db, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
if (count($data) === 0) {
$data[] = array_keys($row);
}
$data[] = [
$row['Priority'],
intval($row['Automated']),
intval($row['isAutomatable']),
intval($row['isNotAutomatable']),
];
}
mysqli_close($db);
echo json_encode($data);
}
这也消除了不必要的循环。