开发者

Sorting multi-dimentional array by more than one field

开发者 https://www.devze.com 2022-12-18 13:40 出处:网络
I have the following data: Array ( [0] => Array ( [filename] => def [filesize] => 4096 [filemtime] => 1264683091

I have the following data:

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] => 
  )
)

and I would like to sort it by more than one value. (e.g. by is_dir AND by filename (alphabetically) or by filemtime AND by filename, etc.)

So far I've tried many solutions, none have which worked.

Does anyone know the best PHP algorhythm/function/method to sort this like so?


Use usort and pass your own comparison function to the function.

//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;   
}

You would then use usort like so:

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


array_multisort is a special function to sort multiple or multi-dimensional arrays. I have used it sometime and like it.

0

精彩评论

暂无评论...
验证码 换一张
取 消