2012-04-01 77 views
0

如何在PHP中對二維數組排序。 我要排序的日期,數組的格式如下:PHP中的數組排序

[result] => Array 
     (
      [0] => Array 
       (
        [link] => http://local/node/0 
        [date] => 13158505310 
       ) 

      [1] => Array 
       (
        [link] => http://local/node/1 
        [date] => 13158505311 
       ) 

      [2] => Array 
       (
        [link] => http://local/node/2 
        [date] => 13158505312 

回答

1

使用此

function sortByDateDesc($a, $b) { 
    return strcmp($a["date"], $b["date"]); 
} 

function sortByDateAsc($a, $b) { 

    if ($a['date'] == $b['date']) { 
     return 0; 
    } 
    return ($a['date'] > $b['date']) ? -1 : 1; 
} 

usort($array, 'sortByDateDesc'); //Descending order 
//usort($array, 'sortByDateAsc'); //Asceding order 
+0

我從來沒有穿過usort來,我不得不這樣做'$ B [ '日期'] - $ A ['日期]'爲DESC訂購。 – GoodSp33d 2012-04-01 13:48:20

3

使用usort

usort($array, function($a, $b){ return $a["date"] - $b["date"]; }); 
0

可能是這樣的代碼對您有所幫助....

// Obtain a list of columns 
foreach (data as key => row) { 
    links[key] = row['link']; 
    dates[key] = row['date']; 
} 

// Sort the data with link descending, date ascending 
// Add $data as the last parameter, to sort by the common key 
array_multisort(link, SORT_DESC, date, SORT_ASC, data);