【问题标题】:Sorting multi-dimentional array by more than one field按多个字段对多维数组进行排序
【发布时间】:2010-01-28 14:25:33
【问题描述】:

我有以下数据:

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

我想按多个值对其进行排序。 (例如,通过 is_dir 和文件名(按字母顺序)或通过 filemtime 和文件名等)

到目前为止,我已经尝试了很多解决方案,但都没有奏效。

有谁知道最好的 PHP 算法/函数/方法来这样排序?

【问题讨论】:

    标签: php sorting arrays multidimensional-array


    【解决方案1】:

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

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

    然后你会像这样使用 usort:

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

    【讨论】:

    • 谢谢。我以为我以前尝试过,但显然没有,因为它有效。
    【解决方案2】:

    array_multisort 是对多维或多维数组进行排序的特殊函数。我曾经使用过它并且喜欢它。

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2013-05-02
      • 2011-03-15
      相关资源
      最近更新 更多