Firstly, how are you wanting this finished array to be structured? Because the example you posted is chaotic at best.
For example, this is the structure of your example finished array,
Code: Select all
Array
(
[FOLDER1] => Array
(
[0] => subfolder1
[subfolder2] => Array
(
[0] => sub_subfolder1
[1] => sub_subfolder12
)
)
[FOLDER2] => Array
(
[0] => subfolder1
)
)
As you can see the key structure keeps changing and where you store the 'folder names' is changing too. May I suggest the following format instead?
Code: Select all
Array
(
[FOLDER1] => Array
(
[subfolder1] => false
[subfolder2] => Array
(
[sub_subfolder1] => false
[sub_subfolder12] => false
)
)
[FOLDER2] => Array
(
[subfolder1] => false
)
[FOLDER3] => false
)
As you can see, in this one, the folders are the keys for the array, and if they contain sub folders, that is then the value for that key.
So, to answer your original question, to parse your array of strings into this format, you can use the following function,
Code: Select all
function createStructure ($strings) {
if (!is_array ($strings)) { return false; }
$finalarray = array ();
foreach ($strings as $string) {
$folders = split ("\.", $string);
$currentfolder = &$finalarray;
foreach ($folders as $folder) {
if (!is_array ($currentfolder)) {
$currentfolder = array ();
}
if (!isset ($currentfolder[$folder])) {
$currentfolder[$folder] = false;
}
$currentfolder = &$currentfolder[$folder];
}
}
return $finalarray;
}
FYI, if the strings are in a file and not an array, load the text file then do a split("\n",$file); to get the strings into an array.