Jump to content

sort directories by date


newb

Recommended Posts

hi, how can i put these results into an array and sort by the $date variable?

 

$dir = "/home/public_html";	
$count = 0;

if ($handle = opendir("$dir")) {
	while (($file = readdir($handle)) !== false) {
	$date = date("F d Y H:i:s.",filemtime("$dir/$file"));
	$file = str_replace('www.domain.com', '', $file); 
	if (preg_match("/.domain.com/i",$file)) {
	$file = substr($file, 4);  
	$count = $count + 1;
	echo "$count. <a href='http://$file'>$file</a> - $date<br />";
	}
	}
closedir($handle);	
echo "<br /><br />$count";
}

Link to comment
https://forums.phpfreaks.com/topic/167642-sort-directories-by-date/
Share on other sites

Like this?

 

<?php
$files = array();

foreach (new DirectoryIterator('/some/path') as $file) {
if ($file->isDir()) continue;

$files[] = array(
	'name' => $file->getFilename(),
	'changed' => $file->getMTime(),
);
}

$count = count($files);

usort($files, create_function('$a,$b', 'return $a["changed"] < $b["changed"];'));

 

If you use PHP 5.3 you can replace the last line with

usort($files, function ($a, $b) {
return $a['changed'] < $b['changed'];
});

ok im using this code:

$dir = "/var/www/";
$count = 0;	

if ($handle = opendir("$dir")) {
	while (($file = readdir($handle)) !== false) {
	$date = date("F d Y H:i:s.",filemtime("$dir/$file"));

	$file = str_replace('www.domain.com', '', $file); 
		if (preg_match("/.domain.com/i",$file)) {
		$file = substr($file, 4);  
		$count = $count + 1;

		$files = array();
		$files[0] = $file;
		$files[1] = $date;

usort($files, function ($a, $b) {
return $a[1] > $b[1];
});

		echo "$count. <a href='http://$file'>$files[0]</a> - $files[1]<br />";
		}
	}

closedir($handle);
echo "<br /><br />$count";

}

 

but it doesnt sort the results by the date, just flips the date inplace of where the domain.com links were at....

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.