【问题标题】:include files on date in directory在目录中包含日期的文件
【发布时间】:2013-11-10 16:30:03
【问题描述】:

好的,我有一个我曾经/正在工作的网站的概述。对于每个站点,我都有一个 php 文件。在该 php 文件中,我使用此代码获取文件的最新和最旧日期,注意目录中的图片。

$date = "test/*.*";
$files = array_filter(glob($date), function($file) {
    $ext = substr($file, strrpos($file, '.'));
    return !in_array($ext, array('.jpg', '.bit', '.png', '.jpeg', '.gif', '.bmp'));
});
$latest = count($files)-1 ;

array_multisort(
    array_map( 'filemtime', $files ),
    SORT_NUMERIC,
    SORT_ASC,
    $files
);
$newestfile = date ("d F Y ", filemtime($files[0]));
$oldestfile = date ("d F Y ", filemtime($files[$latest]));
if($newestfile == $oldestfile) {
    echo  date ("d F Y ", filemtime($files[0]));
} else {
    echo  date ("d F Y ", filemtime($files[0]));
    echo "   -   " ;
    echo  date ("d F Y .", filemtime($files[$latest]));
}

此代码的输出将类似于:2013 年 1 月 16 日 - 2013 年 10 月 25 日。

在我的概览页面中,我使用代码将(我创建的网站的)所有 php 文件包含到该页面。 (顺便说一句。php 文件不是很大的页面。只有一张图片和一点文字。)

$listy = glob("sites/*.php");
print_r ($listy) ;
array_multisort(
    array_map( 'filemtime', $listy ),
    SORT_NUMERIC,
    SORT_DESC,
    $listy
);
if (empty($listy)) {
    include('includes/emptycontent.php');
} else {
    foreach ($listy as $filename) {
        include $filename;
    }
}

这个数组的输出是这样的:

Array ( 
    [0] => sites/test.php 
    [1] => sites/test2.php 
    [2] => sites/test3.php

到目前为止一切顺利,没有任何问题。

现在,我想不按包含文件的时间对包含文件进行排序,就像我在上面的代码中所做的那样。但我希望它对目录中文件的最新日期进行排序,就像在 php 文件中一样。所以实际上我想将这些代码合并为一个。 所以我有一个名为 test.php 的 php 文件。我想要目录中最新文件的日期,也称为测试。它们总是同名。

我的想法是使用第二个代码的输出,然后去掉“sites/”和“.php”。我认为这些名字必须在一个数组中。然后为每个名称获取最新的文件,并将它们从最新到最旧排序。

我认为这样可以将我最近工作的网站放在页面顶部,将较旧的网站放在页面底部。 也许我的方法完全错误,但我不知道如何在代码中做到这一点。

【问题讨论】:

    标签: php arrays date include directory


    【解决方案1】:

    看看这个:

    array_map( 'filemtime', $listy ),
    

    在这里,您实际上是将文件列表转换为修改日期列表。如何将其转换为另一个功能。在目录中找到最新文件的方法:

    array_map(function ($filename) {
        // $filename = sites/test1.php
        $dir = substr($filename, strlen("sites/"), - strlen(".php")); // cut those! 
        // or:
        $dir = basename($filename, '.php');
    
        // put the code listing files inside $dir 
        // then sort it (you did it in the first part)
        // and then `return` the most or the least recent one
    
    }, $listy),
    

    HTH。

    【讨论】:

    • 我认为这是一个很好的方法。但我真的不知道如何在正确的代码中做到这一点。对不起,我还不是一个真正优秀的程序员。我在代码中犯了很多简单的错误。
    猜你喜欢
    • 2018-04-14
    • 2019-08-13
    • 1970-01-01
    • 2023-04-07
    • 2018-04-14
    • 2013-06-21
    • 2020-01-10
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多