使用 glob 和 array_slice 时排除文件名

Exclude file name when using glob and array_slice

这必须很简单:我正在使用 glob 构建目录中所有文件的链接列表(即 index.php、somefile.php、someotherfile.php),但我需要在 array_slice.

之前排除文件 name/path index.php

出于某种原因,在这两个示例中,我可以在 array_alice 之后排除 index.php,但不能排除之前。我做错了什么?

这不会删除文件name/path index.php:

chdir('/dir/tree/');

foreach (glob("*.php") as $path) {

$files[$path] = filemtime($path);

} arsort($files);

if($path != 'index.php') {

foreach (array_slice($files, 0, 3) as $path => $timestamp) {

print '<a href="'. $path .'">'. $path .'</a><br />';
}
}

这会删除 index.php,但它在 array_alice 之后,所以我打印了两个链接而不是三个:

chdir('/dir/tree/');

foreach (glob("*.php") as $path) {

$files[$path] = filemtime($path);

} arsort($files);

foreach (array_slice($files, 0, 3) as $path => $timestamp) {

if($path != 'index.php') {

print '<a href="'. $path .'">'. $path .'</a><br />';
}
}

您正在循环后进行检查。

<php
foreach (glob("*.php") as $path) {
//---------------------------^
    $files[$path] = filemtime($path);
}
arsort($files);

if($path != 'index.php') {}
//---^

像这样把它放在你的循环中:

foreach (glob("*.php") as $path) {
    if($path == 'index.php') {
        continue;
    }
    $files[$path] = filemtime($path);
}