Page 1 of 1

Ordering an Array of File paths by Date newest First

Posted: Mon Jul 09, 2007 5:55 am
by designerman
Hi all I have a script which searches a directory recursivly for filenames and create an array of filepaths complete with filename. I then use this to create a download interface. I need to now modify this script so it displays the newest first but I am having many problems with this i have tried a qsort algorithem but that wasn't what I wanted. I have also tried to write a conditional which I am sure should only add the recent files to the array but this has not worked either.

If anyone can help that would be really great. Please check my code below and show me where I am going wrong.

Code: Select all

//Directory to start in
$baseDir = 'FreeSamples';

//Recursivly read files

Function listdir($start_dir='.') {

  $files = array();
  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      # loop through the files, skipping . and .., and recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
      $filepath = $start_dir . '/' . $file;
      if ( is_dir($filepath) )
        $files = array_merge($files, listdir($filepath));
      else
        array_push($files, $filepath);
    }
    closedir($fh);
  } else {
    # false if the function was called with an invalid non-directory argument
    $files = false;
  }

  return $files;

}

//Call the function and scan dirs
$files = listdir($baseDir);

//Make Array only files added in last week - this is not working!!
$newest_files = array();
foreach($files as $file){
	$current = time();
	if (($current - 60*60*24*7) < filemtime($file)){
		array_push($newest_files, $file);
	}
}

//Sort array so that newest is first - this is not working!!

function DateCmp($a, $b)
{
  return (filemtime($a) < filemtime($b)) ? -1 : 0;
}
usort($files, 'DateCmp'); 

//Make it the top 10 by chopping array off
array_splice($files, 10);
I think the bug lies in the DateCmp function and the foreach I run on the files. If anyone can show me what is going wrong please provide a working example of this code - or just a few snippets if you can :)

Thanks

Posted: Mon Jul 09, 2007 6:38 am
by volka
http://de2.php.net/usort wrote:The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Your function only returns "equal to, or greater than zero"

Posted: Mon Jul 09, 2007 8:03 am
by designerman
Yeh the problem was the -1 : 0 should be -1 : 1 thanks for spotting that its working now!