Sometimes when deleting information, you need to delete everything under this information. In this case, you need to delete it recursively. The following is a piece of code that I wrote to recursively delete a department and all its sub-departments when I was doing the department deletion function in department management. For your reference only and for future reference.
The following is a display of a piece of my code:
Copy the code The 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 with topbumen_id as $bumen_id bumen_id
$delsql="delete from lxsm_bumen where bumen_id=".$bumen_id; //Delete department information with bumen_id $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: The topbumen_id here is the ID number of the superior department in the department information, and the fetch_assoc() function is its own encapsulated function, which is obtained from the query All contents are returned as an array.
Experience: This is my first time writing a recursive algorithm, and it is still very immature. However, the function is realized. I feel that when writing recursive code, you should first draw a tree structure. After recognizing its structure, you can first simulate the step-by-step execution in your mind according to the effect you want to obtain. For example, if you want to delete a department, you have to delete yourself and find the sub-departments with yourself as the superior department, and traverse the sub-departments one by one. At this time, the operation of the sub-department is the same as that of its superior department. Just like deletion, you need to delete itself and search for its sub-departments. In this way, there will be a similar repeated operation. The operations of sub-departments and the operations of superior departments go through the same steps, so let it be used in the traversal of sub-departments. Execute this function itself. This forms a recursive algorithm.
http://www.bkjia.com/PHPjc/743577.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/743577.htmlTechArticleSometimes when deleting information, you need to delete everything under this information. Recursively deleted. The following is when I am doing the delete department function in department management...