简体   繁体   English

获取具有最新日期的文件夹

[英]Get folder with most recent date

I have task where i have to find most recent added folder (which are named by dates). 我的任务是必须找到最新添加的文件夹(按日期命名)。 The problem is that when i fetch dir with all folders with date my array contains full path of folder not only date folder. 问题是,当我获取所有带有日期的文件夹的目录时,数组不仅包含日期文件夹,还包含文件夹的完整路径。 Let mi give you and example of my code and sample out put... 让mi给您和我的代码示例,并提供示例输出...

This is my code 这是我的代码

$dirs = array_filter(glob(__DIR__ . '/../../../var/Html/*'), 'is_dir');
var_dump($dirs);
$mostRecent= 0;
foreach($dirs as $date){
    $curDate = strtotime($date);
    if ($curDate > $mostRecent) {
        $mostRecent = $curDate;
    }
}
var_dump($mostRecent);
die();

And this is the output i get 这是我得到的输出

D:\wamp64\www\mypage\public_html\rest>php index.php cli/pars parseFiles
array(2) {
  [0]=>
  string(111) "D:\wamp64\www\mypage\public_html\rest\application\controllers\cli/../../../var/Html/2017-07-15"
  [1]=>
  string(111) "D:\wamp64\www\mypage\public_html\rest\application\controllers\cli/../../../var/Html/2017-07-16"
}
int(0)

So i believe that the problem is because var $dirs contains full path of my dirs instead only date folder name. 所以我认为问题是因为var $ dirs包含我目录的完整路径,而不是仅日期文件夹名称。 How can i overcome my problem? 我该如何克服我的问题? Thank you 谢谢

The solution to your code is as below. 您的代码的解决方案如下。 basename will give you the folder name from full path string. basename将使用完整路径字符串为您提供文件夹名称。

$dirs = array_filter(glob(__DIR__ . '/../../../var/Html/*'), 'is_dir');
var_dump($dirs);
$mostRecent= 0;
foreach($dirs as $date){
    $curDate = strtotime(basename($date));
    if ($curDate > $mostRecent) {
        $mostRecent = $curDate;
    }
}
var_dump($mostRecent);
die();

basename() — Returns trailing name component of path. basename() —返回路径的尾随名称部分。

In your case it will look like: 在您的情况下,它将看起来像:

$dirs = array_filter(glob(__DIR__ . '/../../../var/Html/*'), 'is_dir');

foreach($dirs as $dir) {
    var_dump(basename($dir));
}

Output: 输出:

string(10) "2017-07-15"
string(10) "2017-07-16"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM