代码之家  ›  专栏  ›  技术社区  ›  BlueDogRanch

使用glob和数组切片时排除文件名

  •  0
  • BlueDogRanch  · 技术社区  · 7 年前

    这必须很简单:我使用glob构建一个目录中所有文件的链接列表(即index.php、somefile.php、someotherfile.php),但我需要排除文件名/路径 index.php array_slice .

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

    这不会删除文件名/路径 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文件 ,但它在数组“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 />';
    }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Narek    7 年前

    你在一个接一个地检查。

    <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);
    }