将数据从MySQL导出到JSON文件[重复]

omqzjyyz  于 2023-03-13  发布在  Mysql
关注(0)|答案(1)|浏览(174)

此问题在此处已有答案

JSON encode MySQL results(16个答案)
1小时前关闭。
在天气表的MySQL数据库中,我有从我的气象站获取的天气数据。我想从这些数据中创建一个JSON文件,这样数据就会显示在图表上。不幸的是,每一条记录都写在一个单独的“列”中,请看:

[{
"0":
"date": "08:57:00"
"temperatura": "7.9"
"wspeed": "5.8"
"1":
"date": "09:57:00"
"temperatura": "9.9"
"wspeed": "4.7"
"2":
"date": "10:57:00"
"temperatura": "11.9"
"wspeed": "6.7"
}]

我希望JSON文件的结构如下所示:

[{
"temperatura":
[2023-03-13 08:57:00, 7.9],[2023-03-13 09:57:00, 9.9],[2023-03-13 10:57:00, 11.9]
"wspeed":[2023-03-13 08:57:00, 5.8],[2023-03-13 09:57:00, 4.7],[2023-03-13 10:57:00, 6.7]
}]

好让HighCharts能读懂整件事。
我的代码:

$sql = "select * from weather";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);
slhcrj9b

slhcrj9b1#

这将解决您的问题:

$sql = "SELECT * FROM weather";
$result = mysqli_query($connection, $sql);

$data = array();
while($row = mysqli_fetch_assoc($result)) {
    $date = $row['date'];
    $temperature = $row['temperatura'];
    $wspeed = $row['wspeed'];

    $data['temperatura'][] = array($date, $temperature);
    $data['wspeed'][] = array($date, $wspeed);
}

echo json_encode(array($data));

相关问题