我想获取父目录的所有子目录中的所有文件名。这是代码:
$rep = '.';
if (file_exists($rep))
{
$myDirectory = opendir($rep);
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
$resultat = "";
for($index=0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != "." && is_dir($dirArray[$index]) && is_numeric($dirArray[$index]))
{
$resultat .= $dirArray[$index].";"; // dossier de photos d'un client
$repClient = $dirArray[$index];
$clientDirectory = opendir($repClient);
while($photoName = readdir($clientDirectory))
{
$photoArray[] = $photoName;
}
closedir($clientDirectory);
$photoCount = count($photoArray);
sort($photoArray);
for ($img = 0; $img < $photoCount ; $img++)
{
if (substr("$photoArray[$img]", 0, 1) != ".")
{
$resultat .= $photoArray[$img].";";
}
}
echo "$resultat<br/>";
}
}
}
我的问题是父目录中实际上有两个子目录,这两个子目录中的每一个只有一个文件(分别是photo31.png和photo32.png)。当我打开包含此脚本的网页时,我得到了这个输出:
7455573;photo31.png;
7455573;photo31.png;7455575;photo31.png;photo32.png;
那么为什么photo31.png
文件仍然存在于输出的第二行?
答案 0 :(得分:2)
您问题的直接答案是:因为您在迭代子目录之间不重置$photoArray
变量。因此,当您查看第二个子目录时,$photoArray
仍然包含您在查看第一个子目录时放入其中的项目。
在此处(for
之前)重置“结果”字符串:
$resultat = "";
您还需要重置$photoArray
:
$resultat = "";
$photoArray = array();
除此之外,代码作为一个整体肯定可以使用一些改进。你有这个代码:
$myDirectory = opendir($rep);
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
然后,在for
循环内,您再次拥有相同的代码(变量名称会更改,但它们会相同)。您可能想尝试创建一个递归实现,调用自己“进入”目录而不是手动这样做。