开发者

How can I get files from a directory and show them by date/time with PHP?

I'm looking for a way to show al开发者_JS百科l of my XML files in a directory. Glob doesn't sort by date, at least I don't think, and can only be used on the same directory... How can I do this?


You can very well use glob, but need some extra code to sort it afterwards:

$files = glob("subdir/*");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);

This will give you an associative array of the form $filename => $timestamp.


Not quite as pretty, but may allow for extra features:

<?php
    // directory to scan
    $dir = 'lib';

    // put list of files into $files
    $files = scandir($dir);

    // remove self ('.') and parent ('..') from list
    $files = array_diff($files, array('.', '..'));

    foreach ($files as $file) {
        // make a path
        $path = $dir . '/' . $file;

        // verify the file exists and we can read it
        if (is_file($path) && file_exists($path) && is_readable($path)) {
            $sorted[] = array(
                'ctime'=>filectime($path),
                'mtime'=>filemtime($path),
                'atime'=>fileatime($path),
                'filename'=>$path,
                'filesize'=>filesize($path)
            );
        }
    }

    // sort by index (ctime)
    asort($sorted);

    // reindex and show our sorted array
    print_r(array_values($sorted));
?>

Output:

Array
(
    [0] => Array
        (
            [ctime] => 1289415301
            [mtime] => 1289415301
            [atime] => 1299182410
            [filename] => lib/example_lib3.php
            [filesize] => 36104
        )

    [1] => Array
        (
            [ctime] => 1297202755
            [mtime] => 1297202722
            [atime] => 1297202721
            [filename] => lib/example_lib1.php
            [filesize] => 16721
        )

    [2] => Array
        (
            [ctime] => 1297365112
            [mtime] => 1297365112
            [atime] => 1297365109
            [filename] => lib/example_lib2.php
            [filesize] => 57778
        )

)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜