php traverses the files in the directory and sorts them by modification time
- 2021-12-13 07:41:20
- OfStack
In this paper, the example tells php traverses the files under the directory and sorts the operation according to the modification time. Share it for your reference, as follows:
Method of php Traversing Files in Directory
// Method of traversing files in directory
function printdir($dir)
{
$files = array();
//opendir() Open directory handle
if($handle = @opendir($dir)){
//readdir() From the directory handle ( resource , formerly by opendir() Open) Read entries ,
// If not, return false
while(($file = readdir($handle)) !== false){// Read an entry
if( $file != ".." && $file != "."){// Exclude Root Directory
if(is_dir($dir . "/" . $file)) {// If file Is a directory, recursive
$files[$file] = printdir($dir . "/" . $file);
} else {
// Get the file modification date
$filetime = date('Y-m-d H:i:s', filemtime($dir . "/" . $file));
// File modification time as key value
$files[$filetime] = $file;
}
}
}
@closedir($handle);
return $files;
}
}
Sort the returned array by time
// Sort arrays according to modification time
function arraysort($aa) {
if( is_array($aa)){
ksort($aa);
foreach($aa as $key => $value) {
if (is_array($value)) {
$arr[$key] = arraysort($value);
} else {
$arr[$key] = $value;
}
}
return $arr;
} else {
return $aa;
}
}
$dir = "/php";
// Output /php All files under
print_r(arraysort(printdir($dir)));
More readers interested in PHP can check the topics of this site: "php File Operation Summary", "PHP Directory Operation Skills Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"
I hope this article is helpful to everyone's PHP programming.