我有一个名为数据的文件夹。在此数据文件夹中,有文件和文件夹。在这个文件夹中有文件和文件夹....继续这样......
我需要获取所有文件路径(包括子目录'文件)。 我有一个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
)
答案 0 :(得分:1)
<?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);
答案 1 :(得分:0)
function dirToArray($dir, &$contents) {
foreach (scandir($dir) as $node) {
if ($node == '.' || $node == '.htaccess' || $node == '..' || $node == '.tmb' || $node == '.quarantine') continue;
if (is_dir($dir . '/' . $node)) {
dirToArray($dir . '/' . $node, $contents);
} else {
$contents[] = $dir . '/' . $node;
}
}
}
$contents = array();
dirToArray( '/var/www/image/data/', $contents );
print_r($contents);
答案 2 :(得分:0)
只是一些评论。
与@dyachenko的OP相同。
你正在检查is_dir(),同时添加$ node作为文件名来检查,这意味着,这永远不会成立,因为你总是得到文件。
第二:dirToArray()里面的if语句完全没有意义,因为它在$content[] = $dir . '/' . $node
运行之前不会做任何事情,如果if语句为真则不会运行。
所以正确的代码是:
function dirToArray($dir, &$contents) {
foreach (scandir($dir) as $node) {
if ($node == '.' || $node == '.htaccess' || $node == '..' || $node == '.tmb' || $node == '.quarantine') continue;
if (is_dir($dir)) {
$contents[] = $dir . '/' . $node;
}
else {
//error or what ever
}
}
}
$contents = array();
dirToArray( '/var/www/html/UusProjekt/intl', $contents );
print_r($contents);