2012-01-21 133 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