Solved

PHP -- Sort array via modified time?

Posted on 2010-11-18
6
786 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 109

Expert Comment

by:Ray Paseur
ID: 34166115
0
 
LVL 109

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 109

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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
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 109

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Need to combine two scripts 2 34
XML extra information 8 30
Custom Wordpress Loop 22 39
MSSQL - Lock Row from reading by other programs 9 40
Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

821 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