按日期排序JSON - PHP


Sort JSON date by date - PHP

我有一个网站抓取合流博客数据。我使用的API似乎没有排序功能。谁能帮我得到PHP排序的JSON日期在页面上的帖子,我需要最近的第一。谢谢!

<?php
require_once($_SERVER["DOCUMENT_ROOT"].'/layout/layout.inc.php');
require_once($_SERVER["DOCUMENT_ROOT"].'/functions/general.inc.php');
$layout = new my_layout();
$layout->title('IT KB Search');
$layout->content("<div class='border'>");
$layout->content('<h1>IT Support Knowledge Base - Search Results</h1>');
    $baseUrl = 'https://website.atlassian.net/wiki';
    $url = $baseUrl.'/rest/api/content?spaceKey=KB&type=blogpost&start=0&limit=10&expand=space,history,body.view,metadata.labels';
    // To enable authenticated search: 
    // $url .= "&os_username=$username&os_password=$password";
    $response = file_get_contents($url);
    $response = json_decode($response);
    $results = $response->results;
    $html .= '<dl style=list-style: none;>';
    foreach($results as $item) {
        $date = $item-> history-> createdDate;
        $html .= '<strong><a href="';
        $html .= $baseUrl. $item-> _links-> webui;
        $html .= '" target="_blank">';
        $html .= $item->title;
        $html .= ' - ';
        $html .= date("d/m/Y",strtotime($date));
        $html .= '</a></strong><br>';
        $html .= $item->body-> view-> value;
        $html .= '<br>';
    }
    $html .= '</dl>';
    $layout->content($html);
$layout->content('</div>');
$layout->render();

foreach循环之前,您可以像这样使用usort

usort($results, function ($a, $b) {
    return strtotime($a->history->createdDate) - strtotime($b->history-> createdDate);
});

一旦完成,$result将以排序的顺序显示数据$a-$b将以升序$b-$a将以降序

显示数据

您可以尝试这样做:-

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($results, 'date_compare');

你可以在你的php文件中声明函数date_compare,并使用如下语句:-

usort($results, 'date_compare');

在for循环前