I have an array such as:
Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 20
http://us2.php.net/manual/en/function.array-multisort.php see third example:
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.
You can simply solve this problem using usort() with callback function. No need to write any custom function.
$your_date_field_name = 'datetime';
usort($your_given_array_name, function ($a, $b) use (&$your_date_field_name) {
return strtotime($a[$your_date_field_name]) - strtotime($b[$your_date_field_name]);
});
This should work. I converted the date to unix time via strtotime.
foreach ($originalArray as $key => $part) {
$sort[$key] = strtotime($part['datetime']);
}
array_multisort($sort, SORT_DESC, $originalArray);
One-liner version would be using multiple array methods:
array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
SORT_DESC,
$originalArray);
For 'd/m/Y'
dates:
usort($array, function ($a, $b, $i = 'datetime') {
$t1 = strtotime(str_replace('/', '-', $a[$i]));
$t2 = strtotime(str_replace('/', '-', $b[$i]));
return $t1 > $t2;
});
where $i
is the array index