PHP 在嵌套循环中超出内存分配

问题描述 投票:0回答:2

我正在解析一个字符串。如果它满足特定条件,我想将新字符附加到另一个子字符串,直到它不再满足该条件和/或字符串末尾。

代码基本如下:

//loop through all the text
for ($i = 0; $i < strlen($text); $i++) {
    //set a boolean to enter and exit the while loop
    $check = true;
    //get the first letter at the ith position
    $substr = $text[$i];
    //start the while loop
    while ($check)
    {
        //check to see if the next character added to the string will be in some group of object keys
        if (array_key_exists(implode("", array($substr, $text[$i + 1]), $objectsKeys)))
        {
            //if it is, append it to the substring
            $substr = implode("", array($substr, $text[$i + 1]));
            //increment i
            $i++;
            //and try the next character
        }
        else
        {
            //otherwise, exit the loop
            $check = false;
        }
    }
}

//set the "letter" to be the substring - not too important for the application...
$letter = $substr;

以下错误是:

PHP message: PHP Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to allocate 20480 bytes)...

我通常不会用 PHP 或 C 编写代码,因为我必须担心内存管理,因此简要回顾一下正在发生的事情以及如何修复它对未来很有帮助。

php loops memory-management
2个回答
0
投票

您可以通过设置以下标志来增加内存:

ini_set('max_execution_time', '0');
ini_set('memory_limit', '1024M');

0
投票

我认为抛出错误的原因是因为在某些时候索引不存在......所以它不应该是内存分配错误,而是索引不存在错误。

这意味着当我处于 while 循环中时,在检查键是否作为子字符串 (

if (array_key_exists(implode("", array($substr , $text[$i + 1])), $objectsKeys))
) 存在之前,我需要检查以确保下一个字符的索引小于
strlen($text);
所以.. .
if ($i + 1 < strlen($text)) {...}
,这意味着我还必须添加 else 语句以确保如果 $i + 1 大于文本的长度,它会退出 while 循环 (
else { $check = false; }
)。

© www.soinside.com 2019 - 2024. All rights reserved.