PHP中的数组排序

时间:2012-04-01 13:29:47

标签: php sorting

如何在PHP中对2D数组进行排序。 我想按日期排序,Array采用以下格式:

[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

5 个答案:

答案 0 :(得分:3)

使用usort

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

答案 1 :(得分: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

答案 2 :(得分:0)

答案 3 :(得分:0)

答案 4 :(得分: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);