Sorting two-dimensional array by date
Is there a way I can sort the following array into the correct chronological order ?
[0] => Array
(
[date] => Sat, 12 Feb 2011 16:55:13 -0500
[title] => Product 1
[link] => http://blabla/product-1
)
[1] => Array
(
[date] => Sat, 25 Sep 2010 17:52:24 -0400
[title] => Product 2
[link] => http://blabla/product-2
)
[2] => Array
(
[date] => Sun, 05 Dec 2010 17:41:32 -0500
[title] => Product 3
[link] => http://blabla/product-3
)
[3] => Array
(
[date] => Sun, 28 Nov 2010 09:14:39 -0500
[title] => Product 4
[link] => http://blabla/product-4
)
[4] => Array
(
[date] => Tue, 07 Dec 2010 18:43:45 -0500
[title] => Product 5
[link] =开发者_StackOverflow> http://blabla/product-5
)
The array, from a rss feed, comes to me like this.
I would like to sort the array in chronological order (based on [date] obviously) : Product 1, Product 5, Product 3, Product 4, Product 2
In order to be able to do display the latest products in the real order (not in the strange order they gave me ! - btw, fake products names, the order is really totally random)
Thanks a lot !
Use usort: http://www.phpbuilder.com/manual/function.usort.php
You write a comparison function that compares two "elements" (in this case, your date strings), and returns the correct order for them.
Edit: you could use strtotime: http://php.net/manual/en/function.strtotime.php to convert the date string to a timestamp, and then return the comparison of the resulting timestamps.
You can use array_multisort
to order the original array according to the order of a sorted array of date values:
$keyValues = array();
foreach ($arr as $item) {
$keyValues[] = strtotime($item['date']);
}
sort($keyValues);
array_multisort($arr, $keyValues);
Use usort function . http://php.net/manual/en/function.usort.php
精彩评论