Let\'s say I have this string which I want to put in a multidimensional array.
Edit : The number of subfolders in the string are dynamic .. from zero sub folders to
This can be solved recursively in another way by taking the items from the beginning of the array and when the last item is reached just return it.
function make_tree( $arr ){
if( count($arr) === 1){
return array_pop( $arr );
}else{
$result[ array_shift( $arr )] = make_tree( $arr ) ;
}
return $result;
}
$string = "Folder1/Folder2/Folder3/filename1\n";
$string .= "Folder1/Folder2/Folder3/filename2\n";
$string .= "Folder4/Folder2/Folder3/filename3\n";
$string = trim( $string );
$files_paths = explode( PHP_EOL, $string);
$result = [];
foreach ($files_paths as $key => $value) {
$parted = explode( '/', $value );
$tree = make_tree( $parted );
$result = array_merge_recursive( $result, $tree );
}
var_dump( $result );