我有一个比较复杂的for
循环,它获取给定目录中某些文件的名称。
我的文件夹目录看起来像这样:
C:'xampp'htdocs'reports
2016-08-16
2016-08-17
2016-08-15
2016-08-14
2016-08-13
2016-08-12
...
在每个文件夹中,都有子文件夹
01.43.19
03.43.19
05.43.20
07.43.20
...
每个子文件夹包含一个.json
文件,目录类似于:
报告文件
reports/2016-08-17/05.43.20/Default Report Name2016-08-17.json
我正在尝试编写一个for
循环,或一系列for
循环,检索 days
, reports
和 report files
所有这些动态创建的数量,因为我不知道有多少文件夹将存在于我的最终产品中。
这是我到目前为止得到的:(要点)。
<?php
//get days and add them to day[this][]
if ($handle = opendir('C:'xampp'htdocs'reports'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$day[][] = $file; // two D day - $day[x][y] - all days stored in X!
}
}
$day = array_reverse($day); // reverse to give the latest day first
}
//get reports and add them to day[][this]
for ($j = 0; $j < count($day[0]) && $j < 5; $j++) // only get the reports for the latest 5 days (if there are more than 5 folders)
{
if ($handle1 = opendir("C:''xampp''htdocs''reports''". $day[$j][0] . "''"))
{
while (false !== ($file = readdir($handle1)))
{
if ($file != "." && $file != "..")
{
$day[$j][] = $file;
}
}
// just to test results
for ($k = 1; $k < count($day[$j]); $k++) // start at 1 as we don't want to count the actual 'day' files
{
echo "<br> Report: " . $day[$j][$k];
}
}
$jsonFilesArray[][] = array();
for ($i = 1; $i < count($day[1]); $i++)
{
foreach (glob("reports/".$day[$j][0]."//" . $day[$j][$i] . "//*.json") as $jsonFile)
{
$jsonFilesArray[$i][] = $jsonFile;
}
}
echo "<br> This is the count: " . count($jsonFilesArray);
echo "<br> This is the report: " . $jsonFilesArray[0][0]; // should output something like: reports/2016-08-17/05.43.20/Default Report Name2016-08-17.json
}
?>
我遇到的问题是检索.json
文件/目录,它看起来像这:
reports/2016-08-17/05.43.20/Default Report Name2016-08-17.json
相反,我得到了如下:
谁能告诉我我哪里错了?以及获得所需输出的方法:数组到字符串的转换在C:'xampp'htdocs'php'getStuff.php on线49
reports/2016-08-17/05.43.20/Default Report Name2016-08-17.json
我建议使用symfony/finder
组件,它将大大简化您的代码。你应该能够做类似这样的代码(经过一些调整)
use Symfony'Component'Finder'Finder;
$finder = new Finder();
$finder->name('*.json');
foreach ($finder->in('C:''xampp''htdocs''reports''*''*''') as $file) {
// ... do something with the file
}