scandir() to sort by date modified

后端 未结 3 1713
感动是毒
感动是毒 2020-11-27 16:26

I\'m trying to make scandir(); function go beyond its written limits, I need more than the alpha sorting it currently supports. I need to sort the scandir

3条回答
  •  时光取名叫无心
    2020-11-27 17:17

    This is a great question and Ryon Sherman’s answer provides a solid answer, but I needed a bit more flexibility for my needs so I created this newer function: better_scandir.

    The goal is to allow having scandir sorting order flags work as expected; not just the reverse array sort method in Ryon’s answer. And also explicitly setting SORT_NUMERIC for the array sort since those time values are clearly numbers.

    Usage is like this; just switch out SCANDIR_SORT_DESCENDING to SCANDIR_SORT_ASCENDING or even leave it empty for default:

    better_scandir(, SCANDIR_SORT_DESCENDING);
    

    And here is the function itself:

    function better_scandir($dir, $sorting_order = SCANDIR_SORT_ASCENDING) {
    
      /****************************************************************************/
      // Roll through the scandir values.
      $files = array();
      foreach (scandir($dir, $sorting_order) as $file) {
        if ($file[0] === '.') {
          continue;
        }
        $files[$file] = filemtime($dir . '/' . $file);
      } // foreach
    
      /****************************************************************************/
      // Sort the files array.
      if ($sorting_order == SCANDIR_SORT_ASCENDING) {
        asort($files, SORT_NUMERIC);
      }
      else {
        arsort($files, SORT_NUMERIC);
      }
    
      /****************************************************************************/
      // Set the final return value.
      $ret = array_keys($files);
    
      /****************************************************************************/
      // Return the final value.
      return ($ret) ? $ret : false;
    
    } // better_scandir
    

提交回复
热议问题