php获取文件夹中文件的完整路径
作者:互联网
我有一个命名数据的文件夹.在此数据文件夹中,有文件和文件夹.在这个文件夹中有文件和文件夹….继续这样……
我需要获取所有文件路径(包括子目录的文件).
我有一个PHP代码:
function dirToArray($dir) {
$contents = array();
foreach (scandir($dir) as $node) {
if ($node == '.' || $node == '.htaccess' || $node == '..' || $node == '.tmb' || $node == '.quarantine') continue;
if (is_dir($dir . '/' . $node)) {
$contents[$node] = dirToArray($dir . '/' . $node);
} else {
$contents[] = $node;
}
}
return $contents;
}
$fileData = dirToArray( '/var/www/image/data/' );
print_r($fileData);
输出在this链接.它给我一个数据文件夹树,如下所示:
Array
(
[04.2014] => Array
(
[C] => Array
(
[0] => AMANFTR105260005_001.jpg
[Acki] => Array
(
[0] => 10269990_1407183112891667_859040604_n.jpg
[1] => 10287174_1407183106225001_914722369_n.jpg
[2] => 10307039_1407183109558334_889879385_n.jpg
[3] => 10318614_1407183099558335_776826424_n.jpg
[25763] => Array
(
[0] => 10268126_1407184372891541_1399955485_n.jpg
[1] => 10268256_1407184362891542_462829886_n.jpg
[2] => 10318854_1407184356224876_1056593541_n.jpg
[3] => photo.jpg
)
[73085] => Array
(
[0] => 10261927_1407212376222074_295083908_n.jpg
[1] => 10268368_1407212366222075_706285245_n.jpg
[2] => 10299493_1407212372888741_1318245049_n.jpg
[3] => 10318719_1407212379555407_451060715_n.jpg
)
但我想要这个数组:
Array
(
[0] => /var/www/image/data/04.2014/C/AMANFTR105260005_001.jpg
[1] => /var/www/image/data/04.2014/C/Acki/10269990_1407183112891667_859040604_n.jpg
[2] => /var/www/image/data/04.2014/C/Acki/10287174_1407183106225001_914722369_n.jpg
...
[223] => /var/www/image/data/logo.gif
)
解决方法:
<?php
$path = dirname(__FILE__);
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($objects as $file => $object) {
$basename = $object->getBasename();
if ($basename == '.' or $basename == '..') {
continue;
}
if ($object->isDir()) {
continue;
}
$fileData[] = $object->getPathname();
}
var_export($fileData);
标签:scandir,php,spl 来源: https://codeday.me/bug/20191002/1841036.html