更新:已找到一个解决方案如下所述:但是新的问题构成我不想继续创建问题所以更新这个当我使用ajax传递给html时我得到以下错误响应.forEach不是函数< / p>
代码如下所示是因为现在有2个数组?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im非常naff说到这种类型的东西,但我需要尝试将这2个查询添加到1 ajax我被告知我应该将两个查询添加到外部数组但我不知道如何做到这一点和我得到的例子是$ array = $ other_array
但是我不知道怎么写它任何帮助都会有很大的帮助
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
答案 0 :(得分:3)
你已经完成了大部分工作。要一次性获取数据,您可以组合数组(请参阅盯着$result
的行),然后将其格式化为JSON格式。
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
更多提示:
->query()
和mysqli_query()
)。mysqli_fetch_all()
为您完成。答案 1 :(得分:0)
如果你的2个数组有db结果,你可以这样做:
$return = array (
$result,
$result2
);
echo json_encode($return);
答案 2 :(得分:0)
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
答案 3 :(得分:-1)
这将是一个更合适和方便(从JavaScript大小)的方式
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);