我有一个 MySQL 数据库,其中填充了从 YouTube API v3 接收的数据。我已设法使用以下代码将此数据输出到 JSON 文件中,但是我希望将该数据按日期和时间的降序输出。 json 字符串名为“publishedAt”,格式为“2015-03-26 15:59:35”。我尝试过各种其他类似的答案,但似乎无法让它与 usort 函数一起使用,所以想知道是否有人可以提供帮助。我对 PHP 很陌生,所以请尝试尽可能具体。
谢谢。
<?php
//open connection to mysql db
$connection = mysqli_connect("host","username","password","Dbname") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from database";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
// perform the query and store the result
$result = $connection->query($sql);
//create an array
$songarray = array();
while($row =mysqli_fetch_object($result))
{
$songarray[] = $row;
}
echo json_encode($songarray);
//close the db connection
mysqli_close($connection);
$fp = fopen('jsondata.json', 'w');
fwrite($fp, json_encode($songarray));
fclose($fp);
?>
最佳答案
我建议您修改sql查询以按日期时间对返回的数据进行排序。
根据您的表结构,您可能需要如下内容:
$sql = "select * from database order by date_column_name";
关于php - PHP 中的 MySQL 数据按日期时间对 JSON 数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31070914/