gpt4 book ai didi

php - 更改文件中的格式 JSON 输出?

转载 作者:行者123 更新时间:2023-11-30 21:35:11 25 4
gpt4 key购买 nike

我有下一个 PHP 代码,它使我成为一个包含 SQL 表中数据的 JSON 文件:

<?php
$mysqli = new mysqli('localhost','root','xxxx','xxxx');
$myArray = array();
$result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20");
if ($result) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray,JSON_NUMERIC_CHECK);
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, json_encode($myArray,JSON_NUMERIC_CHECK));
fclose($fp);
}
$result->close();
$mysqli->close();
?>

JSON 文件的输出如下所示:

[{"Datum":"17-01-2019 10:31:39","KleurL":17.68},{"Datum":"17-01-2019 11:10:59","KleurL":71.76},{"Datum":"18-01-2019 08:40:41","KleurL":70.7},{"Datum":"18-01-2019 10:30:01","KleurL":71.03},{"Datum":"18-01-2019 12:05:46","KleurL":70.56},{"Datum":"18-01-2019 14:31:58","KleurL":16.2}]

但我希望看到该文件的输出如下所示:

[
[
17.68,
17-01-2019 10:31:39
],
[
18.11,
17-01-2019 11:15:20
]
]

如何在 JSON 文件中获取此输出?

最佳答案

下面的代码应该可以实现您想要做的事情。此代码已在我的电脑上测试过,似乎运行良好。

<?php $mysqli = new mysqli('localhost', 'root', 'xxxx', 'xxxx');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;

$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}

$output = $output . "[" . $row->KleurL . "," . $row->Datum . "]"; //add each row

$current_row_number++;
}
$output = $output . "]";

echo $output;

$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}

$result->close();
$mysqli->close();

如果你想很好地格式化输出,使用下面的代码:

<?php $mysqli = new mysqli('localhost', 'root', '244466666', 'tkd');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;

$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}

$output = $output . "\n\t" . "[" . "\n\t\t" . $row->KleurL . "," . "\n\t\t" . $row->Datum . "\n\t" . "]"; //add each row

$current_row_number++;
}
$output = $output . "\n]";

// echo $output; //if you want to see the output in the terminal/command prompt
echo "<pre>" . $output . "</pre>"; //if you want to see the output in a browser

$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}

$result->close();
$mysqli->close();

关于php - 更改文件中的格式 JSON 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265720/

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