Solved

PHP -- Sort array via modified time?

Posted on 2010-11-18
6
781 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
  • 4
6 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34166115
0
 
LVL 108

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 108

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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 34

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 108

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

920 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now