Sometimes, when deleting information, you need to delete all the information under this information. This requires recursive deletion. The following is a piece of code that recursively deletes a department and all its sub-departments when I delete a department in department management. For your reference only and future use.
The following shows a piece of my code:
Copy codeThe Code is as follows:
/*
* Modify a department information.
*/
Function del ($ bumen_id ){
$ SQL = "select bumen_id from lxsm_bumen where topbumen_id =". $ bumen_id; // query bumen_id whose topbumen_id is $ bumen_id
$ Delsql = "delete from lxsm_bumen where bumen_id =". $ bumen_id; // delete the department information whose bumen_id is $ bumen_id
$ Xiaji_id = $ this-> DB-> fetch_assoc ($ SQL );
If ($ xiaji_id ){
Foreach ($ xiaji_id as $ id ){
$ Res = $ this-> del ($ id [bumen_id]);
}
}
$ Result = $ this-> DB-> query ($ delsql );
If ($ result ){
Return true;
}
Else {
Return false;
}
}
Note: Here, topbumen_id is the ID of the upper-level department in the department information, and the fetch_assoc () function is a function that has been encapsulated by itself. It is used to return all the queried content into an array.
Experience: This is the first time I have written a recursive algorithm, but it is still very immature. No matter what the function is. I feel that when writing recursive code, I first draw a tree structure, recognize its structure, and then simulate the execution step by step in my mind based on what I want. For example, if you want to delete a department, you have to delete yourself and find out which sub-departments take yourself as the parent department, and traverse the sub-departments one by one, just like the deletion of its parent department, you need to delete yourself and find its sub-departments. In this way, there is a similar duplicate operation, the operations of sub-departments are the same as those of the upper-level departments. Therefore, in the traversal of sub-departments, let it execute this function. This forms a recursive algorithm.