views:

65

answers:

2

Hi.

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?

+2  A: 

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
Yacoby
thank you. I thought i tried that before, but obviously not, as it worked.
Adam M-W
A: 

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

Bakhtiyor