我想从特定路径文件夹ID和sub_folder parent_id中获取文件夹和子文件夹。在这里,我的函数获取文件夹和子文件夹,但没有id和父id。
我想用 id 和父 id 数组。
function getDirectory($path = '.', $level = 1) {
$result = array();
$ignore = array('nbproject', 'src', '.', '..');
$dh = @opendir($path);
$i = 0;
while ($file = readdir($dh)) {
if (!in_array($file, $ignore)) {
if (is_dir($path . '/' . $file)) {
$level++;
$singleResult = array('title' => $file, 'isFolder' => true, 'children' => getDirectory($path . '/' . $file, $level), 'key' => 'node' . $level);
$result[] = $singleResult;
}
}
$i++;
}
closedir($dh);
return $result;
}
$dir = "../UserUpload/Documents/source";
$kevin = getDirectory($dir);
这个函数给我像这样的数组 wiithout id 和父 id
array (size=3)
0 =>
array (size=4)
'title' => string 'mst146' (length=6)
'isFolder' => boolean true
'children' =>
array (size=3)
0 =>
array (size=4)
...
1 =>
array (size=4)
...
2 =>
array (size=4)
...
'key' => string 'node2' (length=5)
1 =>
array (size=4)
'title' => string 't124' (length=4)
'isFolder' => boolean true
'children' =>
array (size=0)
empty
'key' => string 'node3' (length=5)
2 =>
array (size=4)
'title' => string 'test' (length=4)
'isFolder' => boolean true
'children' =>
array (size=0)
empty
'key' => string 'node4' (length=5)
我建议你在单独的类中使用 scandir 函数(以获得更清晰的递归)。
class DirectoryScanner{
public $scannedData;
protected $ignored = array('nbproject', 'src', '.', '..');
public function scanDir($path){
$filesAndDirs = scandir($path);
foreach($filesAndDirs as $key => $dirOrFile){
if(!in_array($dirOrFile, $this->ignored) && is_dir($path . DIRECTORY_SEPARATOR . $dirOrFile)){
$this->scannedData[$path][$key] = $dirOrFile;
$this->scanDir($path . DIRECTORY_SEPARATOR . $dirOrFile);
}
}
}
}
它将输出二维数组,其中第一维的键是找到目录的路径,第二维是目录的顺序(忽略 .&..,文件会导致索引偏移),值是目录的名称。
例如:
Array
(
[/var/www/cluster/private/..../2016-03/] => Array
(
[21] => chity
[25] => export-porovnani
[26] => exporty
)
[/var/www/cluster/private/..../2016-03/export-porovnani] => Array
(
[13] => vsechno
)
)
您可以通过访问 $scannedData 属性从类中获取数据。 最好是创建 geter 并将$scannedData的可用性设置为受保护/私有
希望我能帮到你一点。