PHP sort array by date mysql
I have an array that I would like to sort using a date field from a MySQL database.
Here is an example of a named array news
in my class:
[48] => Array
(
[id] => 14
[type] => 3
[updated] => 2010-04-17 13:54:42
)
[49] => Array
(
[id] => 15
[type] => 3
[updated] => 2010-04-17 13:57:21
)
I want to sort by field updated
.
I have some code that I started, but I'm not sure how to complete it and get it to work.
class ProcessClass {
// ....
function sortNews($x)
{
usort($this->news, array("ProcessClass", "cmp")); //correct sort type?
}
function cmp($a, $b)
{
// missing code
}
Can anyone please help?
a source to share
In most cases, it will be easier to append ORDER BY updated
to the end of the SQL query, however if your data comes from multiple sources and you need to call PHP, you can use usort () to sort the array based on a user-defined function. To use a class function for comparison, the function MUST be static. It can simply compare the value updated
in the array using the strcmp () function , which turns out to return exactly what you need to sort by MySQL formatted date:
class ProcessClass {
// this must be static
static function sort_by_updated($a, $b)
{
return strcmp($a['updated'], $b['updated']);
}
function sortNews()
{
usort($this->news, array("ProcessClass", "sort_by_updated"));
}
If you want to change the sort order, just change the comparison parameters: return strcmp($b['updated'], $a['updated'])
a source to share
Sorting array of records / assoc _arrays using the specified mysql datetime field and in order:
function build_sorter($key, $dir='ASC') {
return function ($a, $b) use ($key, $dir) {
$t1=strtotime(is_array($a)?$a[$key]:$a->$key);
$t2=strtotime(is_array($b)?$b[$key]:$b->$key);
if($t1==$t2) return 0;
return (str_to_upper($dir)=='ASC'?($t1 < $t2):($t1 > $t2)) ? -1 : 1;
};
}
// $sort - key or property name
// $dir - ASC/DESC sort order or empty
usort($arr, build_sorter($sort, $dir));
a source to share