Sorting multi-dimentional array by more than one field

青春壹個敷衍的年華 提交于 2019-12-24 19:33:33

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/2155117/sorting-multi-dimentional-array-by-more-than-one-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!