0

I need to sort array object based on date in descending order using php. I tried following code, but it didn't get expected result. Can you suggest be to do this task. Thanks in advance.

$document_list = array( '01-14-2013', '01-12-2013', '04-05-2016' );
usort($document_list, array($this, "sortByDate"));

function sortByDate($a, $b) {
    return  strcmp($b['createdDate'], $a['createdDate']);
}

When i tried this code, it get wrong output.

Gugan Abu
  • 546
  • 1
  • 4
  • 17

4 Answers4

0

For this approach you need to convert the date format & dates to timestamp.

$document_list = array( '14-01-2013', '12-01-2013', '05-04-2016' );
$document_list= array_map(function($v) {
    return date('Y-m-d', strtotime($v));
}, $document_list);

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

usort($document_list, "sortByDate");

$document_list= array_map(function($v) {
    return date('m-d-Y', strtotime($v));
}, $document_list);

Output

array(3) {
  [0]=>
  string(10) "04-05-2016"
  [1]=>
  string(10) "01-14-2013"
  [2]=>
  string(10) "01-12-2013"
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0
$document_list = array( '01-14-2013', '01-12-2013', '04-05-2016' );
usort($document_list, array($this, "sortByDate"));

function sortByDate($a, $b) {
    if(strtotime($b['createdDate'])<strtotime($a['createdDate'])){
        return $a['createdDate'];
    }else{
        return $b['createdDate'];
    }
}

Try this

Rahul Singh
  • 918
  • 14
  • 31
0

Yo can do some elegant like this using: (usort: Sort an array by values using a user-defined comparison function

<?php
     // Sort the multidimensional array
     usort($document_list, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>
Suresh Sapkota
  • 149
  • 3
  • 7
0

Personally, I found sorting array by date a non-scalable option due to internal collisions of datetime format. Below may not answer the question to full extent, but may help if one works with array fetched from a DB.

Suppose that in your table there is a primary auto-increment "id" column, then you can always ORDER BY id_column DESC. You will receive same result as sorting by date - but much faster.

If for some reason you can't use ORDER BY id DESC directly via SQL, just restructure array in php via these functions depending on your case.


As a side note: to preview your experiments with above php sorting functions, I strongly recommend visualizing the array display via such snippet that I found somewhere on outskirts of php.net -

function visual_arr($arr){
    echo '<pre>';
    print_r($arr);
    echo  '</pre>';
}

to call it - just use this somewhere in your projects' files: visual_arr ($the_array_you_want_to_display_in_human_radable_format). Obviously choose a shorter name for your array ^^

Hope this helps.

Zerus
  • 158
  • 15