Mooticus Mooticus - 1 month ago 11
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!

<?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();

Answer

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

Comments