I'm currently using a something called jstree to create "Folder View" of items on my website. The folders that make up this folder view are saved in the MySQL database as such:
----------------------------------
| id | folder_name | parent_id |
|------+-------------+-----------|
| 1 | Folder 1 | 0 |
|------+-------------+-----------|
| 2 | Folder 2 | 0 |
|------+-------------+-----------|
| 3 | Sub 1 | 1 |
|------+-------------+-----------|
| 4 | Sub 2 | 1 |
|------+-------------+-----------|
| 5 | Sub 3 | 2 |
|------+-------------+-----------|
| 6 | SubSub 1 | 3 |
----------------------------------
On a different page, I'm looking to display the folders, properly arranged in a dropdown box. The output I hope to achieve inside the dropdown would look something like this:
Folder 1
-- Sub 1
---- SubSub 1
-- Sub 2
Folder 2
-- Sub 3
Any thoughts on how to achieve the above? It seems like some form of recursive function to sort through them would work but I'm struggling to get it worked out. Any help would be greatly appreciated.
Edit:
Here's what I have so far. It appears to be working but it's hard to imagine this is the best way to do it. Any improvement ideas?
$folders = [
[ "id" => 1, "folder_name" => "Folder 1", "parent_id" => 0 ],
[ "id" => 2, "folder_name" => "Folder 2", "parent_id" => 0 ],
[ "id" => 3, "folder_name" => "Sub 1", "parent_id" => 1 ],
[ "id" => 4, "folder_name" => "Sub 2", "parent_id" => 1 ],
[ "id" => 5, "folder_name" => "Sub 3", "parent_id" => 2 ],
[ "id" => 6, "folder_name" => "SubSub 1", "parent_id" => 3 ]
];
function sortedFolders( $parentId, $folders, $depth = 0 )
{
if( count( $folders ) == 0 )
{
return "";
}
$str = "";
for( $i = 0; $i < count( $folders ); $i++ )
{
if( $folders[$i]['parent_id'] == $parentId )
{
$newFolders = $folders;
unset( $newFolders[$i] );
$newFolders = array_values( $newFolders );
$str .= "<option value='" . $folders[$i]['id'] . "'>";
for( $j = 0; $j < $depth; $j++ )
{
$str .= "-- ";
}
$str .= $folders[$i]['folder_name'] . "</option>";
$str .= sortedFolders( $folders[$i]['id'], $newFolders, ($depth + 1) );
}
}
return $str;
}
echo sortedFolders( 0, $folders );