gpt4 book ai didi

javascript - PHP 脚本不断以字符串形式返回数值

转载 作者:行者123 更新时间:2023-12-01 01:53:06 26 4
gpt4 key购买 nike

我有 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>

加载图表时返回的数据会导致问题,因为数字以字符串而不是数字的形式返回。关于如何解决此问题有什么想法吗?

最佳答案

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);
}

这也消除了不必要的循环。

关于javascript - PHP 脚本不断以字符串形式返回数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268414/

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