[英]PHP oldest path based on a dir name
I have on my linux machine such folder tree structure: 我的Linux机器上有这样的文件夹树结构:
/dir/yyyy/mm/dd/HH
eg: 例如:
/dir/2014/03/01/08
/dir/2014/03/20/09
/dir/2014/03/01/10
/dir/2014/08/01/10
/dir/2014/12/15/10
/dir/2015/01/01/14
I'd like to get in php what path is the oldest, like this: 我想在php中找到最旧的路径,如下所示:
The oldest path is: 2014-03-01 08
最旧的路径是:
2014-03-01 08
The newest path is: 2015-01-01 14
最新路径是:
2015-01-01 14
How it can be done? 怎么做?
It could be written better but it works 它可以写得更好,但是行得通
$paths = array(
'/dir/2014/03/01/08',
'/dir/2014/03/20/09',
'/dir/2014/03/01/10',
'/dir/2014/08/01/10',
'/dir/2014/12/15/10',
'/dir/2015/01/01/14',
);
$dates = array();
foreach($paths as $path)
{
$matches = array();
preg_match('#([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+)#', $path, $matches);
$dates[$path] = strtotime(sprintf("%s-%s-%s %s:00:00", $matches[2], $matches[3], $matches[4], $matches[5]));
}
asort($dates);
$dates = array_keys($dates);
$oldest = array_shift($dates);
$newest = array_pop($dates);
It changes date find by regex to unixtimestamp then sorts it and returns top and bottom value of sorted array. 它将通过正则表达式查找的日期更改为unixtimestamp,然后对其进行排序,并返回已排序数组的最高和最低值。
Little bit like Pascal style) 有点像Pascal风格)
<?php
$oldest = '';
$newest = '';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./dir/'));
foreach ($iterator as $file => $object) {
if ($iterator->getDepth() === 4) {
$name = $object->getPath();
if ($name > $newest) {
$newest = $name;
}
if (empty($oldest) or $name < $oldest) {
$oldest = $name;
}
}
}
var_export([$oldest, $newest]);
Result: 结果:
array (
0 => './dir/2014/03/01/08',
1 => './dir/2015/01/01/14',
)
All you have to do is loop through each folder and find the directory that has the lowest number. 您要做的就是遍历每个文件夹并找到编号最小的目录。 If you have the file paths stored in a database, it can be easier, but from your question it seems like you want to search the folders.
如果您将文件路径存储在数据库中,则可能会更容易,但是从您的问题看来,您似乎想搜索文件夹。
<?php
$base = 'dir';
$yearLowest = lowestDir($base);
$monthLowest = lowestDir($yearLowest);
$dayLowest = lowestDir($monthLowest);
echo $dayLowest;
function lowestDir($dir) {
$lowest = null;
$handle = opendir($dir);
while(($name = readdir($handle))) {
if($name == '.' || $name == '..') {
continue;
}
if(is_dir($dir.'/'.$name) && ($lowest == null || $name < $lowest)) {
$lowest = $name;
}
}
closedir($handle);
return $dir.'/'.$lowest;
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.