2012-01-21 141 views
0

,如果我有一個這樣的數組(wihin一個循環 - 所以它充滿了當然超過1項):數組排序

$returnArray[] = array("type" => $dirinfo[0],"fileSize" => $this->ByteSize($dirinfo[1]),"fileName" => $dirinfo[2]); 

字段「類型「可以是」文件夾「或」文件「,但它們混合在一起, 所以像文件夾,文件,文件,文件夾,文件夾,文件等

我想排序文件夾上的第一和然後文件...(如Windows文件夾顯示行爲)

我玩過array_multisort,但只是不能讓它工作...我該怎麼做?

他們的例子是這個9though我想同樣的返回數組剛剛整理,而不是一個新的數組:

foreach ($data as $key => $row) { 
    $volume[$key] = $row['volume']; 
    $edition[$key] = $row['edition']; 
} 

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

所以我做了這個:

// tmp try sorting 
     foreach ($returnArray as $key => $row) { 
      $type[$key]   = $row['type']; 
      $fileSize[$key]  = $row['fileSize']; 
      $fileName[$key]  = $row['fileName'] 
     } 

     // Sort the data with volume descending, edition ascending 
     // Add $data as the last parameter, to sort by the common key 
     array_multisort($type, SORT_DESC, $fileName, SORT_ASC, $fileSize, SORT_ASC, $rfileArray); 

回答

2

的第一站這樣的工作是usort

此函數將使用用戶提供的對其值進行排序比較功能。如果你想排序的數組需要按照一些非平凡的標準排序 ,你應該使用這個函數。

基本用法很簡單:

function cmp($a, $b) { 
    if ($a['type'] == $b['type']) { 
     return 0; // equal 
    } 
    // If types are unequal, one is file and the other is folder. 
    // Since folders should go first, they are "smaller". 
    return $a['type'] == 'folder' ? -1 : 1; 
} 

usort($returnArray, "cmp"); 

從PHP 5.3起,你可以寫的比較函數內聯:

usort($returnArray, function($a, $b) { 
    if ($a['type'] == $b['type']) { 
     return 0; 
    } 
    return $a['type'] == 'folder' ? -1 : 1; 
}); 

又見很不錯comparison of array sorting functions

+0

ooooh這就是...(我可以在文件名之後進行另一個排序,以便它的順序爲alphab。) – renevdkooi