I have an array:
Array
(
[0] => 20140929102023_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140804112307_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
I'd like order this array by first 14 characters of strings, that represents a date. I'd like an array like this:
Array
(
[0] => 20140804112307_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140929102023_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
Thanks.
The sort()
function with the natural sorting algorithm should give you the result you are looking for. It's as simple as this.
sort($array, SORT_NATURAL);
This will updat the existing $array
variable, you do not need to store the return of the sort
function. It simply returns true or falseon success and failure.
The sort function will update the keys as well, if for some reason you need to maintain the keys, and just update the order, you can use asort()
.
asort($array, SORT_NATURAL);
PHP has tons of ways to sort arrays, you can find the manual for that here.
There is no need to use natural sorting algorithms. A normal sort() would produce the effect you desire, as it will compare each string "starting from the left". For example "20141002162349_taxonomies.zip" is bigger than "20140929102023_taxonomies" because the fifth character (the first digit of the month) is 1 in the first and 0 in the second (and 1 > 0, even in a string - comparison works with ASCII code points).
So:
<?php
$array = array('20141002162349_taxonomies.zip', '20140929102023_taxonomies.zip', '20140804112307_taxonomies.zip', '20140915175317_taxonomies.zip');
sort($array);
var_dump($array);
Result:
array(4) {
[0]=>
string(29) "20140804112307_taxonomies.zip"
[1]=>
string(29) "20140915175317_taxonomies.zip"
[2]=>
string(29) "20140929102023_taxonomies.zip"
[3]=>
string(29) "20141002162349_taxonomies.zip"
}