按ID排序JSON

时间:2017-07-27 07:40:53

标签: php json sorting

我有以下JSON文件:

[{
    "id": 9,
    "title": "Birthday",
    "description": "Debut Party",
    "start": "2017-07-25T15:01",
    "end": "2017-08-03T00:01",
    "url": "https:\/\/bd.com"
}, {
    "id": 11,
    "title": "Anniversary",
    "description": "First Ann",
    "start": "2017-06-28T15:00",
    "end": "2017-07-08T02:58",
    "url": "https:\/\/anniversary.com\/"
}, {
    "id": 5,
    "title": "Anniversary",
    "description": "First Ann",
    "start": "2017-06-28T15:00",
    "end": "2017-07-08T02:58",
    "url": "https:\/\/anniversary.com\/"
}]

我希望它们使用PHP按id排序,如5,9,11。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

首先解码JSON

$array = json_decode($json,true);

然后使用usort按ID或其他方式排序。

function sortById($a, $b) {
    return $b->id - $a->id;
}
usort($array,"sortById");

答案 1 :(得分:-1)

SELECT * FROM test ORDER BY `id` DESC;

在你的php文件中使用此查询。 例如:

function getPosts()
{
    $connection = mysqli_connect("localhost", "root", "", DatabaseManager::DATABASE_NAME);
    $sqlQuery = "SELECT * FROM posts order by 'id' desc;";
    $result = $connection->query($sqlQuery);
    $postsArray = array();
    if ($result->num_rows > 0) {
        for ($i = 0; $i < $result->num_rows; $i++) {
            $postsArray[$i] = $result->fetch_assoc();
        }
    }
    echo json_encode($postsArray);
}