0

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
        (
          ------------
        )
)
arjan kroon
  • 803
  • 1
  • 8
  • 21

3 Answers3

2

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

Tx.

arjan kroon
  • 803
  • 1
  • 8
  • 21
0
<?php
$date= array("08-12-2015"=>"lemon", "09-12-2015"=>"orange", "07-12-2015"=>"banana", "c"=>"apple");
ksort($date);
foreach ($date as $key => $val) {
    echo "$date = $val\n";
}
?>

Something like this might be what you're looking for. Just customize it for your needs. So if you already have an array of these dates you can just pass that into the ksort();

RepeaterCreeper
  • 382
  • 3
  • 21
0

convert your key to strtotime($key) then apply ksort($dates) but it will eliminate the duplicate key.

Henrique Barcelos
  • 7,422
  • 1
  • 40
  • 65
wui
  • 380
  • 3
  • 9