Jump to content

Sort images by date


yengec

Recommended Posts

There are two different codes. both works. but how will sort images by date? Where and how do I use filemtime. Thank you.

 

First Code:

$scandir_array = scandir('files');
foreach($scandir_array as $folder){
	if(is_dir('files/'.$folder) and $folder!='.' and $folder!='..'){
		// define this key in the array, it will be blank, store categories as keys
		$categories_array[$folder] = array();
		// $total_photos_array[$folder] = 0;
		$files_in_dir = scandir('files/'.$folder);
		foreach($files_in_dir as $file){
			if($file!='.' and $file!='..'){
				// if file is not the category thumbnail (thumbnail.jpg) and not _thumb.jpg and not _small.jpg
				if($file != "thumbnail.jpg" and substr($file, strlen($file)-10) != "_small.jpg" and substr($file, strlen($file)-10) != "_thumb.jpg"){
					// $total_photos_array[$folder]++;
					$base_file_name = substr($file, 0,  strlen($file)-4);
					// insert this file in the array of files
					array_push($categories_array[$folder], $base_file_name);
					
				}
			}
		}
	}
}
krsort($categories_array);

Second Code:

if ($handle = opendir('files')) {
    while (false !== ($folder = readdir($handle))) {
		if(is_dir('files/'.$folder) and $folder!='.' and $folder!='..'){
			
			// define this key in the array, it will be blank, store categories as keys
			$categories_array[$folder] = array();

			// $total_photos_array[$folder] = 0;
			
			$files_in_dir = scandir('files/'.$folder);
			foreach($files_in_dir as $file){
				// if file ends in _thumb.jpg
				if(strpos($file, '_thumb.jpg') === strlen($file)-10){
					// $total_photos_array[$folder]++;
					$base_file_name = substr($file, 0,  strlen($file)-10);
					// insert this file in the array of files
					array_push($categories_array[$folder], $base_file_name);
				}
			}
			
		}
    }
    closedir($handle);
}
krsort($categories_array);

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

Instead of having $categories_array[$folder] be an array of filenames, have it be an array of filenames => modification times. That's where you use filemtime().

$categories_array[$folder][$base_file_name] = filemtime('files/' . $folder . '/' . $file);
After the files loop finishes (and before you move onto the next folder), asort the $categories_array[$folder] array.
Link to comment
https://forums.phpfreaks.com/topic/294578-sort-images-by-date/#findComment-1505848
Share on other sites

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.