【问题标题】:Get folder with most recent date获取最近日期的文件夹
【发布时间】:2017-11-18 22:32:33
【问题描述】:

我有一个任务,我必须找到最近添加的文件夹(按日期命名)。问题是,当我获取包含日期的所有文件夹的目录时,我的数组不仅包含日期文件夹,还包含文件夹的完整路径。让我给你和我​​的代码示例和示例输出......

这是我的代码

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

这是我得到的输出

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)

所以我认为问题是因为 var $dirs 包含我的目录的完整路径,而不是仅日期文件夹名称。我怎样才能克服我的问题?谢谢

【问题讨论】:

  • 您可以使用basename()获取您要查找的目录。
  • 而且如果你把这些结果放在一个数组中,你可以很容易地对数组进行排序。

标签: php codeigniter codeigniter-3


【解决方案1】:

您的代码的解决方案如下。 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();

【讨论】:

    【解决方案2】:

    basename() — 返回路径的尾随名称组件。

    在你的情况下,它看起来像:

    $dirs = array_filter(glob(__DIR__ . '/../../../var/Html/*'), 'is_dir');
    
    foreach($dirs as $dir) {
        var_dump(basename($dir));
    }
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多