【问题标题】:Exclude file name when using glob and array_slice使用 glob 和 array_slice 时排除文件名
【发布时间】:2018-11-20 20:45:13
【问题描述】:

这必须很简单:我正在使用 glob 构建指向目录中所有文件的链接列表(即 index.php、somefile.php、someotherfile.php),但我需要排除文件名/path index.phparray_slice 之前。

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

这不会删除文件名/路径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 />';
}
}

【问题讨论】:

  • 你在循环后使用$path,所以它总是取最后一项。把它放在第一个循环中。
  • 你能添加一个例子作为答案吗?

标签: php arrays glob


【解决方案1】:

你在循环之后检查。

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

【讨论】:

  • 谢谢!这样可行。我在 $path 之前尝试过 continue 条件但没有让它工作。
猜你喜欢
  • 1970-01-01
  • 2019-12-26
  • 2021-05-06
  • 1970-01-01
  • 2020-03-24
  • 2012-09-19
  • 1970-01-01
  • 2020-12-12
  • 2016-01-14
相关资源
最近更新 更多