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:
- $files = array(
- '1400889600' => 'my-file-1.jpg',
- '1400961491' => 'my-file-2.jpg',
- '1400972101' => 'my-file-3.jpg',
- '1400860153' => 'my-file-4.jpg'
- );
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:
- ksort($files);
This would also work if we had a multidimensional array like so:
- $files = array(
- '1400889600' => array(
- 'filename' = >'my-file-1.jpg',
- 'modified_by' = >'Mr Harris'
- ),
- '1400961491' => array(
- 'filename' = >'my-file-2.jpg',
- 'modified_by' = >'Mr Jones'
- ),
- '1400972101' => array(
- 'filename' = >'my-file-3.jpg',
- 'modified_by' = >'Mrs Brown'
- ),
- '1400860153' => array(
- 'filename' = >'my-file-4.jpg',
- 'modified_by' = >'Ms Smith'
- ),
- );
Simply run the array through the ksort() function and you’d have the items in date ascending order.
0 comments:
Post a Comment