-5

I want to sort the array on date basis.

I used the below code to sort the array

<?php
$a=array("14-10-2013","15-10-2013","16-10-2013","13-11-2013","17-11-2013","18-10-2013","19-10-2013");
array_multisort($a);
print_r($a);
?>

this gives me the result

Array ( [0] => 13-11-2013 [1] => 14-10-2013 [2] => 15-10-2013 [3] => 16-10-2013 [4] => 17-11-2013 [5] => 18-10-2013 [6] => 19-10-2013 ) 

this is not the correct order.

the correct order should be

Array ( [0] => 14-10-2013 [1] => 15-10-2013 [2] => 16-10-2013 [3] => 18-10-2013 [4] => 19-10-2013 [5] => 13-11-2013 [6] => 17-11-2013 ) 

What should i have to do for the correct sequence of the date?

Amrish Khatri
  • 120
  • 1
  • 1
  • 7

2 Answers2

2

use this code :

$a=array("14-10-2013","15-10-2013","16-10-2013","13-11-2013","17-11-2013","18-10-2013","19-10-2013");

usort($a, "sortFunction");

print_r($a);

function sortFunction( $a, $b ) {
    return strtotime($a) - strtotime($b);
}

OUTPUT


Array
(
    [0] => 14-10-2013
    [1] => 15-10-2013
    [2] => 16-10-2013
    [3] => 18-10-2013
    [4] => 19-10-2013
    [5] => 13-11-2013
    [6] => 17-11-2013
)
Shakti Patel
  • 3,762
  • 4
  • 22
  • 29
0

You have a few options here. Reverse the date: 2013-11-13 for example. You are sorting a string. So it starts with the lowest number. That will only work when you have Year-Month-Date.

You can also use timestamps. So from a timestamp, sort all the value's. After that use:

foreach($a as $key => $value) {
  $a[$key] = date("d-m-Y", $value);
}
print_r($a);
Kevin Walter
  • 6,507
  • 8
  • 28
  • 32