从 PHP 中的 MySQL 数据中按日期时间对 JSON 数据进行排序

Sort JSON data by datetime from MySQL data in PHP

我有一个 MySQL 数据库,其中填充了从 YouTube API v3 收到的数据。我已经设法使用以下代码将此数据输出到 JSON 文件中,但是我希望将该数据按日期和时间的降序输出。 json字符串命名为"publishedAt",格式为“2015-03-2615: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 查询以按日期时间对返回的数据进行排序。

根据您的 table 结构,您需要类似的东西:

$sql = "select * from database order by date_column_name";

尝试将您的 SQL 修改为

$sql = "select * from database sort by publishedAt desc";