I'm making a "photo uploader" project that can get all sub-files and sub-directory of specific folder.
I've used iterator
to get files and directory :
$path = dirname(__FILE__).'/';
use RecursiveIteratorIterator as RII;
use RecursiveDirectoryIterator as RDI;
use RecursiveCallbackFilterIterator as RCFI;
$directory = new RDI($path, RDI::SKIP_DOTS);
$filter = new RCFI($directory, function ($current, $key, $iterator) {
return $current->isDir() || preg_match('/^.+(.jpe?g|.png|.gif)$/i', $current->getPathname()) > 0;
});
$iterator = new RII($filter, RII::SELF_FIRST);
After got them, I want their structure be store into database, into the following table :
column `id` is AUTO_INCREMENT
table `item`
| id | title | type | parent_id |
Like Unix, everything is file, even dir, I use column type
to store folder or file, so I can use only one table.
For example, I got two files and two folder :
test (folder)
-file1.png
-subtest (folder)
--file2.png
And I want to store them like this (just for example, the order of them is not important) :
| id | title | type | parent_id |
-----------------------------------------
| 1 | test | folder | null |
| 2 | file1.png | file | 1 |
| 3 | subtest | folder | 1 |
| 4 | file2.png | file | 3 |
I know how to get I don't know how to get every folder and their parent folder structure into array, then store them into table like above
Finally, I got a solution (Thanks u/colshrapnel) :
The easiest way would be to maintain a directory map manually. Say, after inserting the test directory you will get the id and store the full path in the array, $map[$current->getPathname()] = 1;
and so on. Once getting a new entry, get the dirname($current->getPathname())
and test it against the map to get the parent id
Hence the test/subtest
should give you 3