Created
June 28, 2016 14:43
-
-
Save SalvadorP/d78e676195d166078c8bd14e8bcee099 to your computer and use it in GitHub Desktop.
Way to create recursively a folder tree structure, and read it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang=""> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Create Folders / Read Folders</title> | |
</head> | |
<body> | |
<?php | |
/** | |
* Creates the folder structure given by the array | |
* @param array $folderTree Contains the folder tree | |
*/ | |
function createFolderTree($folderTree) { | |
$paths = array(); | |
foreach($folderTree as $parentFolder => $subFolder) { | |
foreach($subFolder as $subFolder) { | |
$paths[] = $parentFolder.'/'.$subFolder; | |
} | |
} | |
foreach ($paths as $path) { | |
mkdir($path, 0777, true); //mkdir recursive faptastic! | |
} | |
} | |
/** | |
* Reads all the files and directories of the specified path | |
* @param string $path Given path to read all files/folders | |
* @return array Contains all the paths of all files and folders | |
*/ | |
function readFolderTree($path) { | |
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); | |
$contents = ['folders' => [], 'files' => []]; | |
foreach ($rii as $file) { | |
if ($file->isDir()){ | |
$contents['folders'][] = $file->getPathname(); | |
} | |
$contents['files'][] = $file->getPathname(); | |
} | |
return $contents; | |
} | |
$folderTree = [ | |
'f1' => ['sf1', 'sf2'], | |
'f2' => ['sf1', 'sf2','sf3', 'sf4'], | |
'f3' => ['sf1', 'sf2', 'sf3'], | |
'f4' => ['sf1', 'sf2','sf3', 'sf4','sf5', 'sf6'], | |
]; | |
?> | |
<?php | |
createFolderTree($folderTree); | |
$contents = readFolderTree('.'); | |
?> | |
<h2>Folders</h2> | |
<pre><?php print_r($contents['folders']); ?></pre> | |
<hr> | |
<h2>Files</h2> | |
<pre><?php print_r($contents['files']); ?></pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment