排序和重新排列数组元素

时间:2010-11-15 06:43:15

标签: php sorting

$people = array(
    array('id' => 12345,'first_name' => 'Joe1','date' => '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'),
);

我希望这个数组元素按日期排序,然后根据php中日期的升序重新排列数组元素 说后续过程应如下所示,

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')
)

2 个答案:

答案 0 :(得分:0)

请参阅array_multisort示例#3

答案 1 :(得分:0)

如果您想手动(通过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()是比较函数,mdy2ymd()只是帮助MM/DD/YYYY形式上的时间戳。