Showing posts with label PHP date_format. Show all posts
Showing posts with label PHP date_format. Show all posts

Thursday, 30 August 2018

PHP sort array with date as key with date format


This question already has an answer here:


  • How to sort a date array in PHP 4 answers
I have an array as follow: The first key element is a date with the format dd-mm-yyyy
Array
(
    [08-12-2015] => Array
        (
          ------------
        )
    [07-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)

Is it possible to sort this array on the first key value bij date? So the first element is
Array
(
    [07-12-2015] => Array
        (
          ------------
        )
    [08-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)


Yes, I found the solution:
function order_date($a1,$b1) {
    $format = 'd-m-Y';
    $a = strtotime(date_format(DateTime::createFromFormat($format, $a1), 'Y-m-d H:i:s'));
    $b = strtotime(date_format(DateTime::createFromFormat($format, $b1), 'Y-m-d H:i:s'));
    if ($a == $b)
    {
        return 0;
    }
    else if ($a > $b)
    {
        return 1;
    }
    else {
        return -1;
    }
}

uksort($array, "order_date");