PHP 从目录中对文件进行排序并按filemtime()对它们进行排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 从目录中对文件进行排序并按filemtime()对它们进行排序相关的知识,希望对你有一定的参考价值。
function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
{
$files = scandir($dir);
$array = array();
foreach($files as $file)
{
if($file != '.' && $file != '..')
{
$now = time();
$last_modified = filemtime($dir.$file);
$time_passed_array = array();
$diff = $now - $last_modified;
$days = floor($diff / (3600 * 24));
if($days)
{
$time_passed_array['days'] = $days;
}
$diff = $diff - ($days * 3600 * 24);
$hours = floor($diff / 3600);
if($hours)
{
$time_passed_array['hours'] = $hours;
}
$diff = $diff - (3600 * $hours);
$minutes = floor($diff / 60);
if($minutes)
{
$time_passed_array['minutes'] = $minutes;
}
$seconds = $diff - ($minutes * 60);
$time_passed_array['seconds'] = $seconds;
$array[] = array('file' => $file,
'timestamp' => $last_modified,
'date' => date ($date_format, $last_modified),
'time_passed' => $time_passed_array);
}
}
usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));
if($sort_type == 'descending')
{
krsort($array);
}
return array($array, $sort_type);
}
//Example of usage:
$dir = '/home/public_html/my_directory/';
$array = Sort_Directory_Files_By_Last_Modified($dir);
// Info Array
$info = $array[0];
// Sort Type
$sort_type = $array[1];
echo '<h3>'.$dir.'</h3>';
echo 'Order by: Last Modified ('.$sort_type.')<br>';
foreach($info as $key => $detail)
{
echo '<h4>'.$detail['file'].'</h4>';
echo 'Last Modified: '.$detail['date'].'<br>';
$time_passed = '';
foreach($detail['time_passed'] as $type => $value)
{
$time_passed .= $value." ".$type.", ";
}
$time_passed = "<span>".rtrim($time_passed, ", ")."</span> ago";
echo $time_passed."nn";
}
以上是关于PHP 从目录中对文件进行排序并按filemtime()对它们进行排序的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 valueForKey 从 fetch 中对数组进行排序
如何在 PHP 中对多维数组进行排序 [重复]
PHP获得文件创建修改访问时间 filectime() filemtime() fileatime()
如何在 Angularfire2 Angular2 中对 FirebaseListObservable 列表进行排序?
php 在php中对数组函数进行排序
如何在 PHP 中对正文进行排序