【问题标题】:Scandir newest files in array with limitScandir 数组中的最新文件,有限制
【发布时间】:2014-04-12 20:00:53
【问题描述】:

我制作了一个 PHP 脚本来扫描一个目录,它列出了一个数组中的所有文件名,限制为 20。现在它只显示数组的开头。所以如果有 40 个文件,它只显示第一个 0-20,但我们需要 20-40.. 有人可以帮我吗?谢谢!!

<?php

$files = glob('data/*.{png}', GLOB_BRACE);
usort($files, 'filemtime_compare');

function filemtime_compare($a, $b)
{
    return filemtime($a) - filemtime($b);
}

$i = 0;
$show = 20;
foreach($files as $file)
{
    if($i == $show) {
         break;
    } else {
         ++$i;
    }
    $var .= $file . "\n";

}
$fp = fopen("data.txt", "wb");
fwrite($fp, $var);  
fclose($fp);
echo $var;

?>

【问题讨论】:

    标签: php arrays scandir


    【解决方案1】:

    您可以使用 array_chunk() 将 $files 数组拆分为 20 个文件的块。然后使用implode() 将块中的值格式化为单个字符串。用这个替换 foreach 循环:

    $show = 20;
    $files = array_chunk($files, $show);
    $page = 0; // page 0 is 0-19, page 1 is 20-39, etc.
    $var = implode("\n", $files[$page]);
    

    编辑:对于最后 20 个文件,您可以使用 array_slice()

    $files = array_slice($files, -20);
    $var = implode("\n", $files);
    

    【讨论】:

    • 然后使用array_slice()获取最后20个值:$files = array_slice($files, -20);。用那个更新了答案。
    • 谢谢,这不取决于服务器上有多少文件?这个波动有时服务器上有 20 个文件,有时有 120 个文件,但我总是需要最新的 20 个。
    • 没关系。如果数组中的值少于 20 个,则返回所有值。
    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多