簡體   English   中英

基於目錄名稱的PHP最舊路徑

[英]PHP oldest path based on a dir name

我的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

怎么做?

它可以寫得更好,但是行得通

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

它將通過正則表達式查找的日期更改為unixtimestamp,然后對其進行排序,並返回已排序數組的最高和最低值。

有點像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',
)

您要做的就是遍歷每個文件夾並找到編號最小的目錄。 如果您將文件路徑存儲在數據庫中,則可能會更容易,但是從您的問題看來,您似乎想搜索文件夾。

<?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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM