I have a table that contains a directory structure. There is an item ID and a DirectoryID. The DirectoryID refers to an item ID and is, as such, a child directory under the parent directory. An example below:
# ID, DirectoryID, DirectoryName
'1', '0', 'Root Dir'
'2', '0', 'Another Root Dir'
'3', '2', 'TESTING456'
'4', '3', 'TESTING789'
'5', '1', 'TESTINGMORE'
'6', '4', 'RANDOM DIR'
Using PHP, how do I build that into an array that looks like the one below?
$array = [
[2 => 'Another Root Dir',3 => 'TESTING456', 4 => 'TESTING789', 6 => 'RANDOM DIR'],
[1 => 'Root Dir',5 => 'TESTINGMORE']
];
2
Answers
If you mean list of all paths for directory array, first create tree then we’ll iterate it. I will start with JS because it’s more fun.
And here’s the PHP version:
Loop through the root nodes and then for each children.
Output