简体   繁体   中英

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

I'm looking for a way to show all 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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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