按列值对多维数组进行排序[重复]

问题描述 投票:0回答:5

如何在 PHP 中对 2D 数组进行排序。 我想按日期排序,数组是这种格式:

[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
php arrays sorting multidimensional-array
5个回答
3
投票

使用usort

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

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
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.