Generate a tree array from file list array

i have the following array

$files = ['/home/test/www/folder/file.txt','/home/test/www/folder2/file.txt'];

i want to create a representative tree array like the following:

    'home' => [
        'test' => [
            'www' => [
                'folder' => ['file.txt'],
                'foler2' => ['file.txt']

how can i achive that?

Well, how about I lay out the steps i’d take, and you give them a try. (To others reading this: I’m also trying to think if there’s a way to shortcut this with variable variables…)

Step 1: Define a recursive function for what to do with each element of the filename. (Hint: Define a base case, and then decide what to do in the other case. This function should take 2 arrays in; one by reference (the result array) and the other by value (the string parts))

Step 2: Define a receiving array to hold your result.

Step 3: For each file, do step 4 and 5.

Step 4: Explode your string to get the constituent parts. Get rid of the first one (which should be blank).

Step 5: Push your receiving array and the exploded string array into your function.

My original solution to this problem consisted of 12 lines of code (including lines that simply contain “}”, but excluding blank lines and setup/confirmation lines), so it shouldn’t be too hard.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.