Monday 16 July 2018

How to Sort an Array by Date using PHP

How to Sort an Array by Date using PHP

Recently I was working on a date-based script that needed to obtain a list of items and sort them by date. In my scenario it was a list of files and I needed to arrange them by their last modified date.
The first prerequisite is that the key part of the array contains the date in a unix timestamp format. Sticking with the array of filenames mentioned above, an example of this can be found below:

  1. $files = array(  
  2.     '1400889600' => 'my-file-1.jpg',  
  3.     '1400961491' => 'my-file-2.jpg',  
  4.     '1400972101' => 'my-file-3.jpg',  
  5.     '1400860153' => 'my-file-4.jpg'  
  6. );  
Note: If you’re not sure how to convert a date to a unix timestamp check out the strtotime()function.
Now that we have our array in the above format we can sort it using the handy PHP function ksort(). If you haven’t guessed by it’s name, it’s used to sort an array by it’s keys.
In our case we would do as follows:

  1. ksort($files);  
This would also work if we had a multidimensional array like so:

  1. $files = array(  
  2.     '1400889600' => array(  
  3.         'filename' = >'my-file-1.jpg',  
  4.         'modified_by' = >'Mr Harris'  
  5.     ),  
  6.     '1400961491' => array(  
  7.         'filename' = >'my-file-2.jpg',  
  8.         'modified_by' = >'Mr Jones'  
  9.     ),  
  10.     '1400972101' => array(  
  11.         'filename' = >'my-file-3.jpg',  
  12.         'modified_by' = >'Mrs Brown'  
  13.     ),  
  14.     '1400860153' => array(  
  15.         'filename' = >'my-file-4.jpg',  
  16.         'modified_by' = >'Ms Smith'  
  17.     ),  
  18. );  
Simply run the array through the ksort() function and you’d have the items in date ascending order.

0 comments:

Post a Comment