按多个字段对多维数组进行排序 [英] Sorting multi-dimentional array by more than one field

查看:140
本文介绍了按多个字段对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

  Array(
[0] => Array(
[文件名] => def
[文件大小] => 4096
[文件时间] => 1264683091
[is_dir] => 1
[is_file] => ;

[1] =>阵列(
[filename] => abc
[filesize] = >> 4096
[filemtime] => 1264683091
[is_dir] => 1
[is_file] =>

[2] =>数组(
[filename] => Rabbit
[文件大小] => 4096
[filemtime] => 1264683060
[is_dir] => 0
[is_file] = >>

[3] =>数组(
[filename] =>猫头鹰
[filesize] => 4096
[filemtime] => 1264683022
[is_dir] => 0
[is_file] =>


,我想按更多排序多于一个值。 (例如,按is_dir和按文件名(按字母顺序排列)或按filemtime和按文件名等。)



到目前为止,我已经尝试了许多解决方案,但没有一个起作用。 / p>

有人知道最好的PHP算法/函数/方法来排序吗?

解决方案

使用 usort 并传递您自己的比较函数

  //示例比较函数
//这将导致一个列表,该列表首先按is_dir排序,然后按is_dir排序通过文件名
函数cmp($ a,$ b){
//首先检查is_dir是否相同,这意味着我们可以
//通过定义的另一个因子进行排序(在这种情况下,文件名)
if($ a ['is_dir'] == $ b ['is_dir']){
//按文件名比较
return strcmp($ a [' filename'],$ b ['filename']);
}
//否则用is_dir比较,因为它们不相同,并且
// is_dir优先于文件名
return($ a ['is_dir']< $ b ['is_dir'])吗? -1:1;
}

然后您将像这样使用usort:

  usort($ myArray, cmp); 
// $ myArray现在已排序


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

这篇关于按多个字段对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆