Solved

PHP -- Sort array via modified time?

Posted on 2010-11-18
6
790 Views
Last Modified: 2012-05-10
I have this:


function getFiles($dir,$exclude=''){
      
   $handle = opendir($dir);
   for(;(false !== ($readdir = readdir($handle)));){
       if($readdir != '.' && $readdir != '..' && $readdir!=$exclude){
           $path = $dir.'/'.$readdir;          
           if(is_file($path) && !strstr($path,"___"))    {
                       $output[] = array('name'=>$readdir,'mtime'=>filemtime($path));
           }
       }
   }
   
   
   closedir($handle);  
   return isset($output)?$output:false;  
}

mtime is defined as modified time of the file using filemtime.. So if I do something like

$files = getFiles($pathTemp,'index.html');

It will give me an array of files, and I can call it via

      foreach ($files as $file) {
                      echo $file['name'];
                      echo $file['mtime'];
              }

But now that I have this array, how can I sort it properly? I want it to be OLDEST to NEWEST files, so that the oldest files are processed first.. Thanks!
0
Comment
Question by:Valleriani
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
6 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34166115
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34166153
Hmm.. You might want this, too.  Not sure about that.
http://us2.php.net/manual/en/function.uasort.php

Either function might meet your needs.  Example #2 on usort() looks particularly on point.
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 34166267

<?php // RAY_temp_valleriani.php
error_reporting(E_ALL);
echo "<pre>";

// REQUIRED AT PHP5.1+
date_default_timezone_set('America/Chicago');

// FROM THE POST AT EE
function getFiles($dir,$exclude='')
{
    $handle = opendir($dir);
    for(;(false !== ($readdir = readdir($handle)));)
    {
        if($readdir != '.' && $readdir != '..' && $readdir!=$exclude)
        {
            $path = $dir.'/'.$readdir;
            if(is_file($path) && !strstr($path,"___"))
            {
                $output[] = array('name'=>$readdir,'mtime'=>filemtime($path));
            }
        }
    }


    closedir($handle);
    return isset($output)?$output:false;
}

$my_files = getFiles(getcwd());

usort($my_files, 'mtimesort');
var_dump($my_files);


function mtimesort($a, $b)
{
    return strcmp((string)$a["mtime"], (string)$b["mtime"]);
}

Open in new window

0
Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

 
LVL 35

Accepted Solution

by:
gr8gonzo earned 250 total points
ID: 34166284
I've always relied on array_csort, which is just a nice wrapper around the built-in multisort. Here's how you use it:

Step 1: Throw this function into your code:
<?php
function array_csort() {        //coded by Ichier2003
    $args = func_get_args();
    $marray = array_shift($args);
    $msortline = 'return(array_multisort(';
    foreach ($args as $arg) {
        $i++;
        if (is_string($arg)) {
            foreach ($marray as $row) {
                $sortarr[$i][] = $row[$arg];
            }
        } else {
            $sortarr[$i] = $arg;
        }
        $msortline .= '$sortarr['.$i.'],';
    }
    $msortline .= '$marray));';
    eval($msortline);
    return $marray;
}
?>

Step 2: Call it like this to sort the array:
$files = array_csort($files,'mtime',SORT_ASC);

You can use SORT_DESC to go the other way. The nice thing about this function is that you can specify multiple columns for sorting (e.g. sort first by name in ascending order, then by modified date in descending order):

$files = array_csort($files,'name',SORT_ASC,'mtime',SORT_DESC);



0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 34166427
JH: That is a nifty piece of code!  ~Ray
0
 
LVL 7

Author Closing Comment

by:Valleriani
ID: 34166524
Thank you both! Both pieces of coding did the trick. Thanks!
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question