【问题标题】:Recursive code results in allowed memory size to be exhausted递归代码导致允许的内存大小被耗尽
【发布时间】:2020-11-20 03:23:17
【问题描述】:

expected outputExpected input我需要从一个对象数组中创建一个嵌套的依赖对象,其中最里面的对象将包含一个键值对。我通过数组操作做到了这一点,我首先将对象值和键值存储在一个二维数组中,然后使用这个二维数组(修剪过的数组),将具有相同父索引值的两行合并在一起。

function recursiveMerge($rowIdx,$columnIdx,$trimmedArray,$parentArray){
        /*base condition - when no column left to traverse recursively*/
        if($columnIdx<1){
            return($trimmedArray);
        } elseif($rowIdx+1 == count($trimmedArray)){
        /*
            when all the rows are merged for a dropdown column, it calls the
            function for the parent dropdown column
        */
            $trimmedArray=array_values($trimmedArray);
            $parentArray=array_values($parentArray);
            //the unique dropdown values are nested inside its parent column
            $trimmedArray[$rowIdx][$columnIdx-1]=array($trimmedArray[$rowIdx][$columnIdx-1]=>$trimmedArray[$rowIdx][$columnIdx]);
            return(recursiveMerge(0,--$columnIdx,$trimmedArray,$parentArray));
        } else {
                /*
            the rows which have identical parent dependent keys are merged together into 
            the first row and the second row is deleted(unset)
            */
            if($parentArray[$rowIdx][$columnIdx]===$parentArray[$rowIdx+1][$columnIdx]){
                // $trimmedArray[$rowIdx][$columnIdx]=$trimmedArray[$rowIdx][$columnIdx] + $trimmedArray[$rowIdx+1][$columnIdx];
                $trimmedArray[$rowIdx][$columnIdx]=array_merge_custom($trimmedArray[$rowIdx][$columnIdx], $trimmedArray[$rowIdx+1][$columnIdx]);
                unset($parentArray[$rowIdx+1]);         
                $parentArray=array_values($parentArray);

                unset($trimmedArray[$rowIdx+1]);            
                $trimmedArray=array_values($trimmedArray);

                return(recursiveMerge($rowIdx,$columnIdx,$trimmedArray,$parentArray));
            }
            else{
                $trimmedArray[$rowIdx][$columnIdx-1]=array($trimmedArray[$rowIdx][$columnIdx-1]=>$trimmedArray[$rowIdx][$columnIdx]);
                return(recursiveMerge(++$rowIdx,$columnIdx,$trimmedArray,$parentArray));
            }

        }
    }

但是,对于尺寸较小的对象数组可以正常工作。具有较大计数的输入数据会导致致命错误:ALlowed memory size exhausted。

【问题讨论】:

  • 如果您提供具体的输入和预期的输出,我可以帮助您
  • 我附上了输入输出的截图

标签: php arrays recursion memory-leaks nested-object


【解决方案1】:

你有两个选择:

  1. 通过最小化递归或使用不同的、内存占用较少的算法来解决您的问题来节省内存。

  2. 为您的 PHP 进程提供更多内存。在您的php.ini 中查看memory_limit

但请记住:PHP 中的递归深度不是无限的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多