Got this job! Great challenge!
First, I sort the array by the number of folders, so the first one to be processed is the files with the least number of folders (in the root directory).
Then the function iterates through each element of the array and each folder in this element, comparing it with existing elements of the array and, if it exists, places it inside this element as a multidimensional array.
This will work up to two subfolders - / root / sub1 / sub2 - but it is quite simple to add functionality for deeper use.
This code example also displays arrays before / after:
$singleArray = array( '/Web', '/Web/Test1', '/Web/Test2', '/Web/Test2/Subfolder', '/Web/Test3', '/Public' ); echo "<pre>"; print_r($singleArray); $multiArray = array(); //first sort array by how many folders there are so that root folders are processed first usort($singleArray, function($a, $b) { $a_folders = explode("/", $a); $b_folders = explode("/", $b); $a_num = count($a_folders); //number of folders in first $b_num = count($b_folders); //number of folders in second if($a_num > $b_num) return -1; elseif($a_num < $b_num) return 1; else return 0; }); //foreach in array foreach($singleArray as $item){ //get names of folders $folders = explode("/", $item); //if the first folder exists if(in_array($folders[0], $multiArray)){ $key1 = array_search($folders[0], $multiArray); //repeat for subfolder
This will output:
Array ( [0] => /Web [1] => /Web/Test1 [2] => /Web/Test2 [3] => /Web/Test2/Subfolder [4] => /Web/Test3 [5] => /Public ) Array ( [0] => /Web [1] => /Public [2] => /Web/Test1 [3] => /Web/Test2 [4] => /Web/Test3 [5] => /Web/Test2/Subfolder )
source share