Mooticus
Mooticus

Reputation: 49

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

Upvotes: 0

Views: 1374

Answers (2)

Webdev
Webdev

Reputation: 647

You can try something like :-

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

You can declare the function date_compare in your php file and use the statement:-

usort($results, 'date_compare');

just before the for each loop

Upvotes: 0

Hari Darshan
Hari Darshan

Reputation: 1920

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

Upvotes: 4

Related Questions