Mooticus Mooticus - 10 months ago 67
PHP Question

Sort JSON date by date - PHP

I have a site grabbing Confluence blogpost data. The API im using doesn't appear to have a sort feature. Can anyone help me get PHP sorting the posts on the page by the JSON date, i need the most recent first. Thanks!


$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 = '';
$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>';



Answer Source

Before foreach loop, you can use usort like this

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

Once done, $result will have data in sorted order $a-$b will give you data in ascending order and $b-$a will give you data in descending order