doumu6997
2016-11-02 03:41
浏览 169
已采纳

PHP递归函数导致PHP耗尽内存?

Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to
allocate 8192 bytes) in *directory* on line 6

This is the error that's getting thrown when I try and access the page running this script:

$root = '../public_html/';

function proccess($dir) {
    $items = scandir($dir);
    $result = array();
    foreach ($items as $item)
    {
        if (is_dir($item))
            $result[$item] = proccess($item);
        else
            array_push($result, $item);
    }
    return $result;
}

print_r(proccess($root));

What I'm trying to accomplish is to build an associative array representing the directory tree in my public_html directory on my server. I'm trying to create a graphical index for myself...mainly just for fun, but this has turned into a learning experience about recursion!

To my eye, this function looks fairly straightforward and I don't have that many files on my server...so unless I've accidentally created an infinite recursion loop, I don't understand why I'm running out of memory.

The loop logic: scan the root directory, then loop through the resulting array. If it finds another directory, set it's name as the key for the $result array and run proccess() again. If it finds a file, simply push the filename to the $result array.

图片转代码服务由CSDN问答提供 功能建议

 致命错误:*目录中允许的内存大小为805306368字节耗尽(尝试
分配8192字节)  *第6行
   
 
 

当我尝试访问运行此脚本的页面时,这是引发的错误:

   $ root ='../public_html/';
nnfunction proccess($ dir){
 $ items = scandir($ dir); 
 $ result = array(); 
 foreach($ items)  as $ item)
 {
 if if(is_dir($ item))
 $ result [$ item] = proccess($ item); 
 else 
 array_push($ result,$ item); 
} \  n返回$ result; 
} 
 
print_r(proccess($ root)); 
   
 
 

我要完成的是构建一个关联数组 表示我服务器上 public_html 目录中的目录树。 我正在尝试为自己创建一个图形索引...主要是为了好玩,但这已经变成了关于递归的学习体验!

在我看来,这个函数看起来相当简单 我的服务器上没有那么多文件...所以除非我不小心创建了一个无限递归循环,否则我不明白为什么我的内存不足。 < p>循环逻辑:扫描根目录,然后遍历生成的数组。 如果找到另一个目录,请将其名称设置为$ result数组的键,然后再次运行proccess()。 如果找到文件,只需将文件名推送到$ result数组。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpl57372 2016-11-02 03:49
    已采纳

    The problem is scandir also returns . and .., which mean "this directory" and "the parent directory", respectively. SSo you're scanning the same directory infinitely. Just filter those out..

    foreach ($items as $item){
         if($item=="." || $item == "..") continue;
         // rest of the code here...
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题