Expected results:
Data Table Structure:
Code:
#### Folder operation # Folder class Folder {public $ id; public $ parent_id; public $ name; public $ children = array (); function _ construct ($ id, $ parent_id, $ name) {$ this-> id = $ id; $ this-> parent_id = $ parent_id; $ this-> name = $ name ;}## folder tree function folder_tree () {global $ domain_id; global $ mailbox_id; $ folder_arr = mysql: select ("select id, parent_id, name from wm_netdisk_folder where domain_id = $ domain_id and mailbox_id = $ mailbox_id "); $ folders = array (); # convert to the Folder object foreach ($ folder_arr as $ key => $ value) {$ id = $ value ['id']; $ parent_id = $ value ['parent _ id']; $ name = $ value ['name']; $ folders [] = new Folder ($ id, $ parent_id, $ name) ;}# top-level folder id $ top_id = 0; # The first layer of tree data $ top = array (); # other data $ table = array (); foreach ($ folders as $ key =>$ value) {if ($ value-> parent_id ==$ top_id) {$ top [] = $ value ;} else {$ table [] = $ value ;}} tree_help ($ top, $ table); return $ top ;## folder_tree auxiliary function (recursion) function tree_help (& $ top, & $ table) {foreach ($ top as $ a => B B) {$ id = $ B-> id; foreach ($ table as $ c =>$ d) {$ parent_id = $ d-> parent_id; if ($ id = $ parent_id) {$ B-> children [] = $ d; $ record [] = $ parent_id;} tree_help ($ B-> children, $ table );}} # format the folder_tree as an option html clip (recursive) $ chrs = array ('│', 'hangzhou', 'hangzhou', '& nbsp ;'); function to_html ($ datas, $ base_line, & $ rs) {global $ chrs; $ len = count ($ datas); $ count = 0; foreach ($ datas as $ key => $ value) {$ count ++; # hierarchical split string $ line = ''; if ($ count = $ len) {$ line = $ base_line. $ chrs [2];} else {$ line = $ base_line. $ chrs [1] ;}$ id = $ value-> id; $ name = $ value-> name; $ pid = $ value-> parent_id; $ option = "<option value = '$ id' data-pid =' $ pid '> $ line $ name </option>"; $ rs [] = $ option; if (count ($ value-> children)> 0) {if ($ count = $ len) {$ line = $ base_line. $ chrs [3];} else {$ line = $ base_line. $ chrs [0];} to_html ($ value-> children, $ line, $ rs );}}}
Ideas:
1. obtain all the folder information from the data table.
2. Group top layer (parent_id = 0) as $ top and other data as $ table.
3. traverse $ top, find parent_id = $ top-> id in $ table, add it to $ top-> children, and perform the same recursion on $ top-> children, until all data in $ table is classified.
[{"Id": x, "name": y, "children": [...]}]
5. format the data obtained in step 3 as the required html clip.
Unlike python and javascript, the php array transmits a copy when passing between functions. If you need to keep the reference, add & in front of the form parameter &.