【问题标题】:Allowed memory size exhausted in PHP for loopPHP for循环中允许的内存大小耗尽
【发布时间】:2019-04-25 12:53:46
【问题描述】:

当我试图在 PHP 中操作大量数组并将结果作为 HTTP POST 请求的响应返回时,我遇到了一个致命错误:

允许的内存大小为 536870912 字节已用完

我已经尝试设置ini_set('memory_limit', '-1'); 以查看是否得到结果,但没有得到任何类型的响应。在我尝试发出 POST 请求时,邮递员总是崩溃。

数组的起始结构就是这个。机身大小约为25mb。主数组包含大约 22k 个具有这种结构的数组,我只包含了 2 个:

Array
(
    [0] => Array
        (
            [id] => 14
            [isActive] => 1
            [personId] => 0023fff16d353d16a052a267811af53bc8bd42f51f2266a2904ca41db19dfd32_0
            [gender] => m
            [age] => 69
            [linedata_0] => 2018-03-01 17:15:18, 155.59, 294.076; 2018-03-01 17:16:04, 502.968, 249.947; 2018-03-01 17:16:44, 276.837, 270.593; 2018-03-01 17:17:28, 431.68, 371.14; 2018-03-01 17:17:34, 851.622, 355.915
        )

    [1] => Array
        (
            [id] => 180
            [isActive] => 1
            [personId] => 02659982ae8286409cc5bb283089871b62f2bafbbad517941d64e77ecf2b62b1_0
            [gender] => m
            [age] => 69
            [linedata_0] => 2018-03-01 13:20:05, 155.599, 293.841; 2018-03-01 13:20:48, 495.468, 249.582; 2018-03-01 13:21:28, 258.791, 260.748; 2018-03-01 13:23:20, 859.061, 352.237; 2018-03-01 13:23:32, 56.1404, 269.858
        )
)

下面的 php 部分用于操作数组,以便通过分解每个用户的时间戳和坐标来获得预期的最终结果:

$final_result = [];

foreach($query_result as $row)
{
    $line_datas =explode(";",$row["linedata_0"]);
    $linedata = [];
    $final = [];
    $d = [];

    for($s =0; $s < count($line_datas); $s++){
        $line_data = explode(",",$line_datas[$s]);
        $d["timestamp"] = utf8_encode($line_data[0]);
        $d["x"]= utf8_encode($line_data[1]);
        $d["y"] = utf8_encode($line_data[2]);

        array_push($linedata,$d);
    }

    $final["id"]= $row["id"];
    $final["isActive"]= $row["isActive"];
    $final["personId"]= utf8_encode($row["personId"]);
    $final["name"] = NULL;
    $final["gender"] = utf8_encode($row["gender"]);
    $final["age"] = utf8_encode($row["age"]);
    $final["linedata"]=$linedata;

    array_push($final_result, $final);
}

return $final_result;

在我看来,没有无限循环或不良做法可以证明内存问题是合理的。唯一真正的问题可能是需要操作的数组的大小。

有什么建议吗?

【问题讨论】:

  • 我要做的第一个优化步骤是使用从数据库返回的 $result 数组,而不是构建另一个怪物数组。还有数据需要做任何工作,让数据库来做,得到最终的结果数据可以使用,减少PHP层内部的工作。
  • @Accountantم 主要问题是我已经在 SQL 中进行了怪物聚合以获得特定结果。我不认为我可以直接用 MySQL 得到最终的预期结果。这就是为什么我考虑在 PHP 中进行一些转换的原因。
  • 尝试将数据库查询设置为仅获取几行并查看结果是否相同。如果是,那么您必须在未发布的代码中某处存在无限循环。
  • @MagnusEriksson 已检查。使用 LIMIT 它可以正常工作。
  • 我可以想象如果你试图一次性返回这么多数据,邮递员会崩溃。使用一些分页而不是一次全部返回。

标签: php arrays for-loop foreach memory-size


【解决方案1】:

在这种情况下使用大数据是一种不好的做法。

想象一下:你有一个包含 22k 个数组的变量 $a,你开始形成第二个变量 $b,它也将包含 22k 个数组。

所以在你的脚本结束时,你将有 2 个带有 22k 数组的变量。

要避免这些问题,您应该分批获取数据。例如一个循环 500 行。


    function findRows($offset = 0, &$final_result = []) {
        $sql = 'SELECT * FROM my_table LIMIT ' . $offset . ', 500';
        //your code to find rows

        if ($query_result) {
            $offset = $offset + 500;

            foreach($query_result as $row) {
                //your another code
                array_push($final_result, $final);
            }
            findRows($offset, $final_result);
        }

        return $final_result;
    }

    return findRows();

【讨论】:

  • 你能给我看一个根据我现在的代码分批获取数据的例子吗?
  • 我已应用您的解决方案,偏移量为 0,500。但是还是会出现内存大小错误。
  • 而且$final_result 每次都会被替换。因此,使用您的代码,我们将得到 null 作为最终结果。所以一个空数组。
  • 好的,试试这个。因为我之前没有检查代码。这很好用
  • 我不确定.. 但我认为它不能解决内存问题。我们只是拆分操作,但使用内存的成本是相同的。您是否根据内存消耗测试了此解决方案?
【解决方案2】:

这个答案是如何在代码中实现缓冲区(内存中的有限数组)的示例,当它被填充时,将其内容刷新到磁盘,最后你会在磁盘上找到一个 JSON 格式的巨大数组.我在与您类似的情况下使用了这种方式,并且在“内存使用”方面得到了很好的结果,但是正如我在 cmets 中告诉您的那样,您需要重新考虑为什么首先需要那个 HUGE 数组,以及是否有办法避免它,去吧。

使用这个函数可以节省$final_result 数组使用的内存,并用$final_result 字符串缓冲区替换它,但我们正在控制它对内存的使用。但是,您的 $query_result 数组仍会占用它需要的内存。

请注意,您需要根据需要更改函数,因为我使用了代码中未定义的变量。

/**
 * proccess the HUGE array and save it to disk in json format [element,element]
 * 
 * @param string $fileName absulote file name path you want to save the proccessed array in
 * @return int processed elements count
 */
function buildMyArrayInFile($fileName)
{
    $flushCheckPoint = 100;// set the buffer size as needed, depending on the size of PHP allowed memory and average element size
    $processedElements = 0;
    $final_result = "[";

    file_put_contents($fileName, "");//prepare the file and erase anything in it

    foreach($query_result as $row)
    {
        $line_datas =explode(";",$row["linedata_0"]);
        $linedata = [];
        $final = [];
        $d = [];

        for($s =0; $s < count($line_datas); $s++){
            $line_data = explode(",",$line_datas[$s]);
            $d["timestamp"] = utf8_encode($line_data[0]);
            $d["x"]= utf8_encode($line_data[1]);
            $d["y"] = utf8_encode($line_data[2]);

            array_push($linedata,$d);
        }

        $final["id"]= $row["id"];
        $final["isActive"]= $row["isActive"];
        $final["personId"]= utf8_encode($row["personId"]);
        $final["name"] = NULL;
        $final["gender"] = utf8_encode($row["gender"]);
        $final["age"] = utf8_encode($row["age"]);
        $final["linedata"]=$linedata;


        $final_result .= json_encode($final) . ",";
        $processedElements ++;
        if($processedElements % $flushCheckPoint === 0){
            //the array has reached the limit, flush the array to disk
            file_put_contents($fileName, $final_result, FILE_APPEND);
            $final_result = "";
        }

    }

    $final_result = rtrim($final_result, ",");//trim the last comma
    $final_result .= "]";
    //flush the remaning data in $final_result
    file_put_contents($fileName, $final_result, FILE_APPEND);

    return $processedElements;

}

这是另一个用于测试的简单版本的函数

// test
var_dump(buildMyArrayInFile2("/home/myuser/myArray.json"));
// outputs int(7)



function buildMyArrayInFile2($fileName)
{
    $flushCheckPoint = 2;// set the buffer size as needed, depending on the size of PHP allowed memory and average element size
    $processedElements = 0;
    $final_result = "[";

    file_put_contents($fileName, "");//prepare the file and erase anything in it

    $test_result = [1,2,3,4,"wee","hello\nworld",5];
    foreach($test_result as $row)
    {
        $final_result .= json_encode($row) . ",";
        $processedElements ++;
        if($processedElements % $flushCheckPoint === 0){
            //the array has reached the limit, flush the array to disk
            file_put_contents($fileName, $final_result, FILE_APPEND);
            $final_result = "";
        }

    }

    $final_result = rtrim($final_result, ",");//trim the last comma
    $final_result .= "]";
    //flush the remaning data in $final_result
    file_put_contents($fileName, $final_result, FILE_APPEND);

    return $processedElements;
}

【讨论】:

  • 谢谢。给我一些时间看看。
  • 最后我检验了所有假设,包括收益率解决方案。但这是唯一适用于我的解决方案。
【解决方案3】:

您正在将大量数据收集到数组中,然后才将其返回。

如果您改为在 foreach 循环中收集一个 '$final' 项目,并 yield 它,而不是将其放入一个不断增加的变量中,您仍然可以围绕函数调用进行 foreach .

这是一个简单的示例,其中 $i 代表一个样本返回值,而不是您收集的数据的“$final”数组。

<?php
function count_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = count_one_to_three();
foreach ($generator as $value) {  // you can also foreach(count_one_to_three() as $value)
    echo "$value\n";
}

Information on 'yield' in PHP

【讨论】:

  • 感谢您的建议。老实说,我从未听说过yield。我不确定如何在当前代码中正确实现它。从理论上讲,这是否比批处理方法更好?
  • 这就像用yield $final; 替换array_push($final_result, $final); 一样简单,不需要return 任何东西。相反,它在每个循环中将一项返回给调用者,然后从停止的地方继续。该链接有更多详细信息。值得一读 - php.net/manual/en/language.generators.syntax.php
  • 我已经读过了。但老实说,我没有明白它对我的情况有何用处……你能根据我当前的代码给我看一个例子吗?也许解释一下应该是什么优势?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2020-06-25
  • 1970-01-01
  • 2017-12-13
  • 2010-10-20
  • 1970-01-01
  • 2013-10-21
相关资源
最近更新 更多