I have an array such as:
Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 20
Sorting array of records/assoc_arrays by specified mysql datetime field and by 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 (strtoupper($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));