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

标签 php mysql json date usort

我有一个 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/

相关文章:

c# - 无法从使用 C# 开发的 Android 应用程序接收 json

php - Symfony2 QueryBuilder 按 ID 顺序返回产品查询

php - 将 "id' s"分配给 mysql 行以与关联数组一起使用

php - 如何在 SQL (MySQL) 中合并两个表?

javascript - 如何使用 JQuery ajax 调用从 JSON 获取某些数据?

json - 我想使用 Morgan 和 Express 将网络日志存储到 json 文件

php - 如何将静态参数从路由传递到 Controller - Laravel 5

php - 显示数据库中的数据和类别

PHP/mySQL - 在本地准备和绑定(bind)

json字符串解码遇到无效转义