php 为什么每当我使用 scandir() 时,我都会在数组的开头收到句点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7132399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:06:35  来源:igfitidea点击:

Why is it whenever I use scandir() I receive periods at the beginning of the array?

phpdirectory

提问by DividedDreams

Why is it whenever I use scandir() I receive periods at the beginning of the array?

为什么每当我使用 scandir() 时,我都会在数组的开头收到句点?

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

回答by phihag

There are two entries present in every directory listing:

每个目录列表中都有两个条目:

  • .refers to the current directory
  • ..refers to the parent directory (or the root, if the current directory is the root)
  • .指向当前目录
  • ..指父目录(或根目录,如果当前目录是根目录)

You can remove them from the results by filtering them out of the results of scandir:

您可以通过从 scandir 的结果中过滤它们来将它们从结果中删除:

$allFiles = scandir(__DIR__); // Or any other directory
$files = array_diff($allFiles, array('.', '..'));

回答by Mat

Those are the current (.) and parent (..) directories. They are present in all directories, and are used to refer to the directory itself and its direct parent.

这些是当前 ( .) 和父 ( ..) 目录。它们存在于所有目录中,用于引用目录本身及其直接父目录。

回答by Dan Bray

To remove .and ..from scandiruse this function:

要删除...停止scandir使用此功能:

function scandir1($dir)
{
    return array_values(array_diff(scandir($dir), array('..', '.')));
}

The array_valuescommand re-indexes the array so that it starts from 0. If you don't need the array re-indexing, then the accepted answer will work fine. Simply: array_diff(scandir($dir), array('..', '.')).

array_values命令重新索引数组,使其从 0 开始。如果您不需要数组重新索引,那么接受的答案将正常工作。简单地说:array_diff(scandir($dir), array('..', '.'))

回答by Jeremy

In Unix convention . is a link to the current directory while .. is a link to the parent directory. Both of them exist as a file in the directory index.

在 Unix 约定中。是指向当前目录的链接,而 .. 是指向父目录的链接。它们都作为目录索引中的文件存在。

回答by joash

In one line of code:

在一行代码中:

$files=array_slice(scandir('/path/to/directory/'), 2);