使用PHP递归获取最新文件 [英] Get most recent files recursively with PHP

查看:47
本文介绍了使用PHP递归获取最新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找递归列出目录中五个最新文件的代码.

I am looking for code which lists the five most recent files in a directory recursively.

这是非递归代码,如果它是递归的,对我来说将是完美的:

This is non-recursive code, and would be perfect for me if it was recursive:

<?php

$show = 0; // Leave as 0 for all
$dir = 'sat/'; // Leave as blank for current

if($dir) chdir($dir);
$files = glob( '*.{html,php,php4,txt}', GLOB_BRACE );
usort( $files, 'filemtime_compare' );

function filemtime_compare( $a, $b )
{
    return filemtime( $b ) - filemtime( $a );
}
$i = 0;
foreach ( $files as $file )
{
    ++$i;
    if ( $i == $show ) break;
    echo $file . ' - ' . date( 'D, d M y H:i:s', filemtime($file) ) . '<br />' . "\n";  /* This is the output line */
}
?>

是否可以修改它以递归方式扫描目录?

It is possible to modify it to scan directories recursively?

推荐答案

这是我的第一个版本(经过测试,可以正常运行):

This was my first version (tested, working):

function latest($searchDir, array $files = array()) {
    $search = opendir($searchDir);

    $dirs = array();
    while($item = readdir($search)) {
        if ($item == '.' || $item == '..') { continue; }
        if (is_dir($searchDir.'/'.$item)) {
            $dirs[] = $searchDir.'/'.$item;
        }
        if (is_file($searchDir.'/'.$item)) {
            $ftime = filemtime($searchDir.'/'.$item);
            $files[$ftime] = $searchDir.'/'.$item;
        }
    }
    closedir($search);
    if (count($dirs) > 0) {
        foreach ($dirs as $dir) {
            $files += latest($dir,$files);
        }
    }
    krsort($files);
    $files = array_slice($files, 0, 5, true);
    return $files;
}

但是我喜欢byte对 glob()的使用,所以这是他的略微修改版本,可以返回相同的格式:

But I like byte's usage of glob(), so here is a slightly modified version of his to return the same format:

function top5modsEx($dir) {
    $mods = array();
    foreach (glob($dir . '/*') as $f) {
        $mods[filemtime($f)] = $f;
    }
    krsort($mods);
    return array_slice($mods, 0, 5, true);
}

这将返回文件被修改为数组元素的键的时间(UNIX时间戳格式).

This returns the time (UNIX Timestamp format) that the file was modified as the key of the element in the array.

这篇关于使用PHP递归获取最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆