Friday, February 11, 2011

php dir list and sort by date

Even though the php dir function works straight from the box, it won't be very much help when you'll start thinking of sorting a file list by modification date of the file. here is a piece of code and a few functions that do the trick
function comparar($a, $b)
{
return strnatcasecmp($b["1"], $a["1"]); //reversed to order from newest to oldest, change to ($a["1"], $b["1"]) to do oldest to newest
}
$default_dir = "."; //current directory
$dirlist = array(); //make new array
$dir = dir($default_dir);
while($file = $dir->read()) //read directory
{
if(0 != strpos($file, '.demo')) //if filename has .demo in it continue
{
$lastmodified = filemtime($file); //find filetime in milliseconds
$dirlist[] = array($file, $lastmodified); //put these into array
}
}
$dir->close();
usort($dirlist, "comparar"); //send array to usort
$arraynum = sizeof($dirlist); //how many entities the array contains
$i = 0;
while($i < $arraynum) { $curList = $dirlist[$i]; //set current array to access $curFile = $curList[0]; //access that array's first array $curTime = $curList[1]; //access that array's second array $curDate = date("m/d/y", $curTime); //convert time into something readable echo " $curFile $curDate";
$i = $i + 1; //next $i
}

No comments:

Post a Comment