2010-01-28 86 views
0

我有以下數據:由多個字段排序多維陣列

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和按文件名(按字母順序)或通過filemtime和按文件名等)

到目前爲止,我已經嘗試了許多解決方案,沒有一個工作。

有沒有人知道最好的PHP算法/函數/方法來排序這個像這樣?

回答

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 
+0

謝謝。我以爲我曾嘗試過,但顯然不是,因爲它的工作。 – 2010-01-28 14:52:40

0

array_multisort是一個特殊的功能,多個或多維數組進行排序。我曾經使用它並喜歡它。