Solved

PHP -- Sort array via modified time?

Posted on 2010-11-18
6
779 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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
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…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

707 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

18 Experts available now in Live!

Get 1:1 Help Now