PHP超过了嵌套循环中的内存分配



我正在分析一个字符串。如果它满足某个条件,我希望将新字符附加到另一个子字符串,直到它不再满足该条件和/或字符串的末尾。

代码基本如下:

//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编写代码,因为我必须担心内存管理,所以简单回顾一下发生了什么以及如何修复它对未来来说会很好。

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

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

我认为这引发错误的原因是因为在某个时候索引不存在。。。所以这不应该是内存分配错误,而是索引不存在错误。

这意味着,当我在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; }(。

最新更新