允许的内存大小用递归函数耗尽

时间:2016-01-22 15:59:12

标签: php function recursion

尝试通过同一用户捕获多个帐户的一部分,我们在用户登录时放置一个cookie。在登录期间,首先我们尝试读取先前的cookie并将其替换为新的cookie。读写的cookie存储在数据库中。当cookie没有被删除时,该系统可以是识别多账户的一部分。

使用递归函数搜索多个帐户时,内存不足。当不用作递归时,它可以工作,但有时用户有这么多帐户,我们只能通过对所有找到的帐户重复此功能来找到它们。 它重复此功能最多3次,但可以肯定的是,此函数必须运行,直到找不到多个帐户。

function xtest_getOtherNicks($dbh,$nick){
    /**
        Find all duplicate accounts, based on cookie
    */
    $aOtherNicks = array();
    $aCookies = db\ct_getCookies($dbh,$nick);

    foreach($aCookies as $k => $aCookie){

        $aFoundNicks = db\ct_getNick($dbh,$aCookies[$k]['cookiewaarde']);

        if(count($aFoundNicks) > 0){

            foreach($aFoundNicks as $key => $aFoundNick){

                if(!in_array($aFoundNick['nick'],$aOtherNicks)){
                    $aOtherNicks[] = $aFoundNick['nick'];

                    //Recursive part
                    //$aMoreFoundNicks = xtest_getOtherNicks($dbh,$aFoundNick['nick']);
                    /**
                    if(count($aMoreFoundNicks)>0){
                        foreach($aMoreFoundNicks as $key => $aMoreFoundNick){
                            if(!in_array($aMoreFoundNick['nick'],$aOtherNicks)){
                                $aOtherNicks[] = $aMoreFoundNick['nick'];
                            }    
                        }
                    } */

                }
            }
        }
    }

    return $aOtherNicks; 
}

我已经搜索了其他递归问题,但它们与我的不同。也许有可能更改SQL并让数据库完成工作,但我对此部分一无所知。

表:

CREATE TABLE IF NOT EXISTS `cookietest` (
  `cookiewaarde` varchar(100) NOT NULL,
  `nick` varchar(100) NOT NULL,
  `datum` datetime NOT NULL,
  `rw` enum('r','w') NOT NULL,
  KEY `cookiewaarde` (`cookiewaarde`),
  KEY `nick` (`nick`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

查询cookies:

$q = "SELECT 
            cookiewaarde
        FROM
            cookietest
        WHERE
            nick = '".sanitize($nick)."'";// will be converted to PDO

1 个答案:

答案 0 :(得分:1)

您需要将$aOtherNicks传递到递归范围。否则你不会破坏递归循环,因为它将与空数组进行比较(找到的值总是唯一的)。这个shuold工作:

function xtest_getOtherNicks($dbh, $nick, $aOtherNicks = array())
{
    $aCookies = db\ct_getCookies($dbh, $nick);
    foreach ($aCookies as $aCookie) {

        $aFoundNicks = db\ct_getNick($dbh, $aCookie['cookiewaarde']);
        foreach ($aFoundNicks as $aFoundNick) {
            if (in_array($aFoundNick['nick'], $aOtherNicks)) { continue; }
            $aOtherNicks[] = $aFoundNick['nick'];
            $aOtherNicks = xtest_getOtherNicks($dbh, $aFoundNick['nick'], $aOtherNicks);
        }
    }

    return $aOtherNicks;
}