$people = array(
array('id' => 12345,'first_name' => 'Joe1','date' =开发者_如何学Python> '02/06/2011'),
array('id' => 12346,'first_name' => 'Joe','date' => '01/27/2011'),
array('id' => 12347,'first_name' => 'rah','date' => '01/22/2011'),
array('id' => 12348,'first_name' => 'sar','date' => '02/21/2011'),
array('id' => 12349,'first_name' => 'raj','date' => '04/18/2011'),
array('id' => 12350,'first_name' => 'viv','date' => '01/31/2011'),
);
I want this array elements to sort by date and then rearrange the array elements according to the ascending order of date in php say the after process should look like this below on ,
var_export($people);
//answer
array(
array('id' => 12347, 'first_name' => 'rah', 'date' => '01/22/2011'),
array('id' => 12346, 'first_name' => 'Joe', 'date' => '01/27/2011'),
array('id' => 12350, 'first_name' => 'viv', 'date' => '01/31/2011'),
array('id' => 12345, 'first_name' => 'Joe1', 'date' => '02/06/2011'),
array('id' => 12348, 'first_name' => 'sar', 'date' => '02/21/2011'),
array('id' => 12349, 'first_name' => 'raj', 'date' => '04/18/2011')
)
In case you want to do it manually (by means of usort()
):
function mdy2ymd($date) {
$parts = explode('/', $date);
return $parts[2] . $parts[0] . $parts[1]; // YYYYMMDD
}
function sortByDate($a, $b) {
return mdy2ymd($a['date']) - mdy2ymd($b['date']);
}
usort($people, 'sortByDate');
(Demo)
sortByDate()
is the comparison function and mdy2ymd()
is just a helper to make timestamps on the form MM/DD/YYYY
comparable.
See array_multisort example #3
精彩评论