45、PHP 原生魅力 - 文件操作 - 解析目录
如果你需要获取目录中的文件列表(如 ls 命令所做的),你可以使用 scandir() 函数。
<?php
$files = scandir(__DIR__);
print_r($files);
输出如下:
$ php 45-scandir.php
Array
(
[0] => .
[1] => ..
[2] => 44-stat.php
[3] => 45-scandir.php
[4] => test.txt
)
一个目录名(字符串)作为输入将得到一个字符串数组:文件名,目录名,还包括特殊目录,如 . 和 ..。
你可以使用 2 个常量控制排序。默认值为升序排序(按字母顺序)。使用 SCANDIR_SORT_DESCENDING ,你可以得到一个降序的字符串:
<?php
$files = scandir(__DIR__, SCANDIR_SORT_DESCENDING);
print_r($files);
输出如下:
$ php 45-scandir.php
Array
(
[0] => test.txt
[1] => 45-scandir.php
[2] => 44-stat.php
[3] => ..
[4] => .
)
或者,如果你根本不想排序,你可以使用 SCANDIR_SORT_NONE :
$files = scandir(__DIR__, SCANDIR_SORT_NONE);
var_dump($files);
如果要排除 . 和 ..,可以使用如下方法:
<?php
$files = array_diff(scandir(__DIR__), [".", ".."]);
print_r($files);
输出如下:
$ php 45-scandir.php
Array
(
[2] => 44-stat.php
[3] => 45-scandir.php
[4] => test.txt
)
请登录后再评论