Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP -- Sort array via modified time?

Posted on 2010-11-18
6
Medium Priority
?
797 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 111

Expert Comment

by:Ray Paseur
ID: 34166115
0
 
LVL 111

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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 35

Accepted Solution

by:
gr8gonzo earned 1000 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 111

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

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.
This article will show, step by step, how to integrate R code into a R Sweave document
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…
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…

670 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