【问题标题】:PHP opendir(), sorting by datePHP opendir(),按日期排序
【发布时间】:2014-03-10 07:15:13
【问题描述】:

我有一个从目录中检索文件的脚本,需要按日期对文件进行排序。最新照片上传到列表顶部。请给任何人建议?

<?
$slozka = "./gallery/holiday/"; //select the folder from which you want to list files
$thumb= "thumb"; //the name of the folder thumbnails
$vypis = opendir($slozka); //open folder
$celkem = '0'; //beginning number of photos

while (false!==($file = readdir($vypis))) //reading files
{ 
    if($file!="."&&$file!=".."&&!is_dir($file)&&$file!=$thumb) //search through folder
    { 
        $celkem++; //count the number of pictures
        $filetitle = $file;
        $nahrada = array("_", ".jpg", ".png", ".gif");
        $filetitle = str_replace($nahrada, " ", "$filetitle");

        if (file_exists($slozka.$thumb.'/'.$file))
        { //If there is a preview and display it ..
            echo "<li><a href=\"gallery/holiday/".$file."\" alt=\"".$file."\"
title=\"".$filetitle."\" class=\"holiday\" /><img src=\"gallery/holiday/thumb/".$file."\" alt=\"".$file."\"></a><span class=\"nazvy\">".$filetitle."</span></li>";
        }//If there is no way it will create ...
        else 
            echo "<li><a href=\"gallery/holiday/".$file."\" alt=\"".$file."\" class=\"holiday\" /><img src=\"thumb.php?nazev=".$file."&amp;cesta=".$slozka."\" alt=\"".$file."\"></a><span class=\"nazvy\">".$filetitle."</span></li>";
    } 
}     
echo "</ul><div id=\"soucet\">Celkem fotek : ".$celkem."</div>"; // print the number of photos in the gallery ...
closedir($vypis); //close folder
?>

【问题讨论】:

标签: php sorting opendir


【解决方案1】:

您可以使用终端命令find 函数从目录中获取最新文件。反向排序并使用您正在检查的文件模式循环目录。然后,您将在日期之前获得最新的文件。

检查链接以供参考。

https://superuser.com/questions/294161/unix-linux-find-and-sort-by-date-modified

Ex :

find . -type f -name '{$fileFormat}*'.txt -exec ls -tr {} \; | sort -r | head -10
$output = array();
@chdir($destinationDir);
@exec($command, $output);

然后循环$output

【讨论】:

    【解决方案2】:

    你应该搜索过这个。

    很明显opendir() 本身不检索文件修改,也不检索创建日期。

    简单搜索“上次修改的文件”将重定向到这里:

    https://www.google.com/search?q=php+file+modified+last

    第一个结果是 php.net 的文档:

    http://php.net/filemtime

    你可以在哪里使用

    date ("F d Y H:i:s.", filemtime($file)
    

    为了检索您的列表的日期时间时间戳。

    您可以在其顶部构建数组并通过数组排序函数之一对其进行排序 (http://www.php.net/manual/en/array.sorting.php)

    最后但并非最不重要的一点 - 英语是官方编程语言,所以不要像 $celkem$slozka 这样的变量命名

    【讨论】:

    • 但是在这里,您需要检查每个文件并存储其修改后的时间戳,这看起来是一个乏味的过程。你的想法?
    • 您在 while 循环中执行此操作。例如$fileInfo['filename'][] = $file; $fileInfo['modified'][] = date("F d Y H:i:s.", filemtime($file));
    • 所以$fileInfo会变成一个包含文件名和修改的数组
    • 所以这里我们必须循环两次以按日期获取文件列表,然后再次循环 ($fileInfo) 以读取它们。
    • 是的,这就是我的看法。您可以尝试使用谷歌搜索不同的方法。如果有更好的,你可以使用它。老实说,如果你不重复代码,循环两次并没有那么糟糕。如果这种情况你不是。一旦你循环构建必要的数组。两次提取最终用户所需的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    相关资源
    最近更新 更多