2015-01-19 2 views
1

디렉토리와 파일을 인쇄하는 recursivephp 함수를 작성하려고합니다. 나는이 함수를 호출 할 때재귀 파일 목록 기능

이 문제가
<?php 
function recursiveDir($adr){ 
    $dh = opendir($adr); 
    while (false !== ($filename = readdir($dh))) { 
     if(is_dir($adr.'/'.$filename)&& $filename!='.' && $filename!='..'){   
      recursiveDir($adr.'/'.$filename); 
     } elseif($filename!='.' && $filename!='..') { 
      echo $filename.'<br>'; 
     } 
    } 
} 
$dir = getcwd(); 
recursiveDir($dir); 
?> 

, 그것이로 전환 : 그래서 여기에 내 현재 코드 나, 난 그냥 recursive functions 내 기술을 업그레이드하려고 phpRecursiveIteratorIterator를 사용하지만 포인트를하지 이잖아 수있어 무한 루프와 나는 이유를 이해할 수 없다.

+0

는 내가 잘못된 장소 – NimaNr

답변

0

나는 당신의 기능을 테스트 한, 그것은 작동하지만, 내가이 말을 마련 할 :

<?php 
/** 
    * @param String $adr 
    * @param Integer $depth : to show nicely the tree 
    */ 
function recursiveDir($adr, $depth = 0) { 
    $depth++; 
    $dh = opendir ($adr); 

    if(is_null($dh)) { 
     printf ("Can not open this directory %s (may be permission is denied)", $adr); 
     return NULL; 
    } 
    // use upper case for TRUE, FALSE and NULL : PHP recommendation 
    while (FALSE !== ($filename = readdir ($dh))) { 
     // it will be easy for another developer what do you want to escape from execution 
     if ($filename == '.' || $filename == '..') { 
      continue; 
     } 

     if (is_dir ($adr.'\\'.$filename)) {   
      // use printf instead of echo or print, it lets separating between variables and the formatted message    
      printf ("%s DIR: %s.\n", str_repeat ("-", $depth), $adr . '\\' . $filename); 
      recursiveDir ($adr . '\\' . $filename); 
     } elseif (is_file ($adr.'\\'.$filename)) { 
      printf ("%s FILE: %s.\n", str_repeat ("-", $depth + 4), $adr.'\\'.$filename); 
     // ALWAYS : write/do something in uncatched cases ... 
     } else { 
      printf ("Unknown Resource: %s\n", $adr . '\\' . $filename); 
     } 
    } 
    // never forget to close an opened resource 
    closedir ($dh); 
} 
$dir = getcwd(); 
recursiveDir($dir); 
+0

에 loop' 동안 난 당신이 함수를 호출 할 때 생각'넣을 생각 함수 내부에서 다음과 같이 사용할 수 있습니다 : recursiveDir ($ adr. '\\'. $ filename, $ depth + 4); – NimaNr