PHP递归函数删除所有的子节点会导致stackoverflow [英] PHP recursive function to delete all child nodes causes stackoverflow

查看:124
本文介绍了PHP递归函数删除所有的子节点会导致stackoverflow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL看起来像这样:(表名的类别)

 'id','content', 'parent'

其中:


  • id =类别ID

  • content =
    some-text-we-dont-care-about

  • parent =父母的标识
    分类



这就是我现在要做的:

 函数remrecurs($ id){
$ qlist = mysql_query(SELECT * FROM category WHERE parent ='$ id' );
if(mysql_num_rows($ qlist)> 0){
while($ curitem = mysql_fetch_array($ qlist)){
remrecurs($ curitem ['parent']);


mysql_query(DELETE FROM category WHERE id ='$ id');



$ b $ p
$ b

由于某种原因,它不工作并崩溃。我在做什么错?

解决方案

问题出在递归调用中:

  remrecurs($ curitem ['parent']); 

应该是:

  remrecurs($ curitem [ 'ID']); 

为什么?

你的目标是删除给定id的行。首先检查是否有任何孩子。如果是,则需要再次对不在父级上的每个 子级 调用递归删除。你再次在父对象上递归地调用函数..这会导致无限递归调用,你会崩溃堆栈并崩溃。


My MySQL looks like this: (the name of the table is category)

'id', 'content', 'parent'

where:

  • id = the id of the category
  • content = some-text-we-dont-care-about
  • parent = the id of the parent category

this is what I'm trying right now:

function remrecurs($id) {
    $qlist=mysql_query("SELECT * FROM category WHERE parent='$id'");
    if (mysql_num_rows($qlist)>0) {
         while($curitem=mysql_fetch_array($qlist)) {
              remrecurs($curitem['parent']);
         }
    }
    mysql_query("DELETE FROM category WHERE id='$id'");
}

Which for some reason doesnt work and crashes .. Any idea what I'm doing wrong ?

解决方案

The problem is in the recursive call:

remrecurs($curitem['parent']);

it should be:

remrecurs($curitem['id']);

Why?

Your objective is to delete the row with given id. First you check to see if it has any children. If yes you need to call the recursive delete on each of the children not on the parent again. You are calling the function recursively on the parent again..this leads to infinite recursive calls, you thrash the stack and crash.

这篇关于PHP递归函数删除所有的子节点会导致stackoverflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆