我有下一个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文件中获取此输出?
答案 0 :(得分:1)
下面的代码应该可以实现您想要的目的。该代码已在我的PC上进行了测试,似乎运行良好。
<?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();
答案 1 :(得分:0)
您可以使用json_encode() JSON_PRETTY_PRINT
选项:
json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
编辑:
如果您使用的是Windows,则需要使用以下方式更改回车符:
$myArray = array("test" => "data");
$buffer = json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
echo str_replace("\n", "\r\n", $buffer);
// or
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, str_replace("\n", "\r\n", $buffer));
fclose($fp);
如果将其打印到浏览器中,则需要使用<pre>
标签
<pre>
echo json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
</pre>