Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exporting data from MySQL to JSON file

In the mysql database in the weather table I have weather data taken from my weather station. I would like to create a JSON file from this data, thanks to which the data will be shown on the chart.
Unfortunately, each single record is written to a separate "column", look at:

[{
"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"
}]

I would like to make it so that the structure of the JSON file is like this:

[{
"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]
}]

So that the whole thing can be read by HighCharts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my code:

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

>Solution :

This will solve your problem:

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

$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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading