2009-11-27 2 views
0

함수를 사용하여 반복적으로 폴더를 스캔하고 각 스캔의 내용을 배열에 할당하려고합니다.PHP에서 증분 깊이의 배열 동적 구성

next() 또는 foreach를 사용하여 배열의 각 연속 인덱스를 반복 할 수있을만큼 간단하지만 배열에 깊이 레이어를 동적으로 추가하는 방법은 문제가됩니다. 몇 가지 의사가 있습니다 :

function myScanner($start){ 

    static $files = array(); 

    $files = scandir($start); 
    //do some filtering here to omit unwanted types 

    $next = next($files); 


    //recurse scan 

    //PROBLEM: how to increment position in array to store results 
    //$next_position = $files[][][].... ad infinitum 

    //myScanner($start.DIRECTORY_SEPARATOR.$next); 
} 

아이디어가 있습니까?

답변

2

시도 뭔가 :

// $array is a pointer to your array 
// $start is a directory to start the scan 
function myScanner($start, &$array){ 
    // opening $start directory handle 
    $handle = opendir($start); 

    // now we try to read the directory contents 
    while (false !== ($file = readdir($handle))) { 
    // filtering . and .. "folders" 
    if ($file != "." && $file != "..") { 
     // a variable to test if this file is a directory 
     $dirtest = $start . DIRECTORY_SEPARATOR . $file; 

     // check it 
     if (is_dir($dirtest)) { 
     // if it is the directory then run the function again 
     // DIRECTORY_SEPARATOR here to not mix files and directories with the same name 
     myScanner($dirtest, $array[$file . DIRECTORY_SEPARATOR]); 
     } else { 
     // else we just add this file to an array 
     $array[$file] = ''; 
     } 
    } 
    } 

    // closing directory handle 
    closedir($handle); 
} 

// test it 
$mytree = array(); 
myScanner('/var/www', $mytree); 

print "<pre>"; 
print_r($mytree); 
print "</pre>"; 
+0

나는 지금까지 일하지 않고 소용돌이 치다. – sunwukung

+0

다시 시도해 보았는데, 나는 조금 고쳤다. – silent

+0

완벽하게 작동했다. 나는 참조를 사용하는 것에 대해 생각하지 않았다. 이 줄은 입니다. myScanner ($ dirtest, $ array [$ file. DIRECTORY_SEPARATOR]); 은 나를 괴롭힌 것입니다. 연관 키가 추가되는 위치를 보지 못했습니다. 참조가 변수를 시작한다는 것을 알기 전까지는. 나는 오늘 값진 것을 배웠다. – sunwukung

0

이 기능을 사용 (당신의 요구에 대한 편집)보십시오 : 그것은 디렉토리의 정렬 된 배열을 반환

function getDirTree($dir,$p=true) { 
    $d = dir($dir);$x=array(); 
    while (false !== ($r = $d->read())) { 
     if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) { 
      $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false)); 
     } 
    } 

    foreach ($x as $key => $value) { 
     if (is_dir($dir.$key."/")) { 
      $x[$key] = getDirTree($dir.$key."/",$p); 
     } 
    } 

    ksort($x); 
    return $x; 
} 

. 이 같은

+1

많은 감사 .... 는 ...하지만 범죄를 야기하고 싶은없이 - 즉, 상당히 밀도 함수, 그리고 내가 뭔가 조금 완만하고 싶습니다 - 아마로 의견이 있으십니까? – sunwukung