按多个字段对多维数组进行排序

时间:2010-01-28 14:25:34

标签: php sorting arrays multidimensional-array

我有以下数据:

Array ( 
  [0] => Array ( 
         [filename] => def
         [filesize] => 4096 
         [filemtime] => 1264683091 
         [is_dir] => 1 
         [is_file] => 
  ) 
  [1] => Array ( 
         [filename] => abc
         [filesize] => 4096 
         [filemtime] => 1264683091 
         [is_dir] => 1 
         [is_file] => 
  ) 
  [2] => Array ( 
         [filename] => rabbit
         [filesize] => 4096 
         [filemtime] => 1264683060 
         [is_dir] => 0
         [is_file] => 
  )
  [3] => Array ( 
         [filename] => owl
         [filesize] => 4096 
         [filemtime] => 1264683022
         [is_dir] => 0
         [is_file] => 
  )
)

我希望按多个值对其进行排序。 (例如,通过is_dir AND文件名(按字母顺序)或通过filemtime和文件名等。)

到目前为止,我已经尝试了许多解决方案,但没有一个解决方案。

有没有人知道最好的PHP算法/功能/方法来这样排序?

2 个答案:

答案 0 :(得分:3)

使用usort并将您自己的比较函数传递给函数。

//example comparison function
//this results in a list sorted first by is_dir and then by file name
function cmp($a, $b){
    //first check to see if is_dir is the same, which means we can
    //sort by another factor we defined (in this case, filename)
    if ( $a['is_dir'] == $b['is_dir'] ){
        //compares by filename
        return strcmp($a['filename'], $b['filename']);
    }
    //otherwise compare by is_dir, because they are not the same and
    //is_dir takes priority over filename
    return ($a['is_dir'] < $b['is_dir']) ? -1 : 1;   
}

然后你会像这样使用usort:

usort($myArray, "cmp");
//$myArray is now sorted

答案 1 :(得分:0)

array_multisort是一个对多维或多维数组进行排序的特殊函数。我曾经使用它并喜欢它。