文件和文件夹列表

时间:2018-01-12 12:00:20

标签: php

actully我从特定路径获取文件夹和文件,但它不会返回我想要的值。

我希望返回值如下: -

[{"filename":"19_0_0_0_0_1.jpg","RFI":19},
{"filename":"19_0_0_0_0_2.jpg","RFI":19},
{"filename":"19_20005_1_0_0_1.jpg","RFI":19},
{"filename":"19_20005_1_0_0_2.jpg","RFI":19},
{"filename":"19_20005_1_429_0_1.jpg","RFI":19},
{"filename":"19_20005_1_429_0_2.jpg","RFI":19},
{"filename":"19_20005_1_429_1_1.jpg","RFI":19},
{"filename":"19_20005_1_429_1_2.jpg","RFI":19},
{"filename":"19_20027_1_0_0_1.jpg","RFI":19}]

它给我这样的输出:

[{"filename":[{"filename":"19_0_0_0_0_1.jpg","RFI":19},
{"filename":"19_0_0_0_0_2.jpg","RFI":19},
{"filename":"19_20005_1_0_0_1.jpg","RFI":19},
{"filename":"19_20005_1_0_0_2.jpg","RFI":19},
{"filename":"19_20005_1_429_0_1.jpg","RFI":19},
{"filename":"19_20005_1_429_0_2.jpg","RFI":19},
{"filename":"19_20005_1_429_1_1.jpg","RFI":19},
{"filename":"19_20005_1_429_1_2.jpg","RFI":19},
{"filename":"19_20027_1_0_0_1.jpg","RFI":19}],"RFI":19}]

这是我的代码:

$ldir = "D:\php\EIL_App\RFIImages";
$data = listFolderFiles($ldir,19);

print json_encode($data);

function listFolderFiles($dir,$pRFI)
{
    $result = array();
    foreach (new DirectoryIterator($dir) as $fileInfo){
        if (!$fileInfo->isDot()){       
            $dataimg = $fileInfo->getFilename();
            if($fileInfo->getFilename() == $pRFI){
                if ($fileInfo->isDir()){
                    $dataimg = listFolderFiles($fileInfo->getPathname(),$pRFI);
                }
            array_push($result,array('filename'=>$dataimg,'RFI'=>$pRFI));
            }
        }
    }
    return $result;
}

请给出建议我该怎么做???

提前致谢。

1 个答案:

答案 0 :(得分:1)

没有必要使事情复杂化

$prefix = 19;
$dir = "D:\php\EIL_App\RFIImages";
$data = glob("$prefix*.*",19); // it will give you array with all files matching pattern

// then you can do a loop

$arr = [];

foreach ($data as $filename) {
   $arr[] = ['filename' => $filename, 'prefix' => $prefix];
}

echo json_encode($arr);

http://php.net/manual/en/function.glob.php

如果要使用迭代器,请使用glob http://php.net/manual/en/globiterator.construct.php

关于你的代码

if ($fileInfo->isDir())这没有任何意义,因为它永远不会发生这种情况。这是因为在您检查if (!$fileInfo->isDot()){之前,dot表示适用于目录的...。如果你想递归地做,那么你可以使用

修改

我注意到你做了一些递归,如果是的话那么可能最好使用ResursiveIterator

function listFolderFiles($dir, $prefix) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    $files = new RegexIterator($rii, "^$prefix.*", RegexIterator::GET_MATCH); // note prefix cannot have characters that are special to regex or they should be escaped
    $arr = array();

    foreach($files as $file) {
        $arr[] = $file;
    }

    return $arr;
}

http://php.net/manual/en/class.recursivedirectoryiterator.php http://php.net/manual/en/directoryiterator.isdot.php