基于目录名称的PHP最旧路径

时间:2015-03-27 11:00:29

标签: php shell-exec spl

我的linux机器上有这样的文件夹树结构:
/dir/yyyy/mm/dd/HH

例如: -
/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

我想在php中找到最老的路径,如下所示:
最古老的路径是:2014-03-01 08
最新路径为:2015-01-01 14

怎么做?

3 个答案:

答案 0 :(得分:0)

它可以写得更好但是有效

 $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);

它将regex的日期查找更改为unixtimestamp,然后对其进行排序并返回已排序数组的顶部和底部值。

答案 1 :(得分:0)

有点像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]);

结果:

array (
    0 => './dir/2014/03/01/08',
    1 => './dir/2015/01/01/14',
)

答案 2 :(得分:0)

您所要做的就是遍历每个文件夹并找到编号最小的目录。如果您将文件路径存储在数据库中,则可以更容易,但从您的问题来看,您似乎想要搜索文件夹。

<?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;
    }

?>