2012-10-27 3 views
1

PHP 함수에서 여러 값을 반환하고 싶지만 다음 코드와 같이 작동하지 않았습니다.배열에서 여러 값을 반환 할 수없는 이유는 무엇입니까?

이 함수는 특정 폴더와 해당 재귀 폴더의 파일 이름을 검색하고 파일 이름을 배열에 저장하는 데 사용됩니다.

메인 폴더 하위 \ 테스트 \ 하위 7 운반 :
재귀 폴더라고 \ 시험 : F F :이 예에서

은 특정 (주) 폴더라고 파일은 파일 이름 형식은 다음과 같습니다

기본 폴더에 대한

: 1.TXT, 2.txt, 3.txt, 하위 폴더에 대한 4.txt
: 5.txt, 6.txt, 7.txt

function getDirectory($path = '.', $level = 0) { 
$i=0;$j=0; 

$dh = @opendir($path); 
while(false !== ($file = readdir($dh))){ 
// Loop through the directory 

     if(is_dir("$path/$file")){ 
     // Its a directory, so we need to keep reading down... 

      getDirectory("$path/$file", ($level+1)); 
      // Re-call this same function but on a new directory, this is what makes function recursive. 

     } else { 
      if ($level>0) //in a recursive folder 
      { 
       $dir_matched[$j]=$file; 
       $j++; 
      } 
      else //in main folder 
      { 
      $files_matched[$i] = $file; 
      $i++; 
      }    
     }  
} 
closedir($dh); 
//print_r ($files_matched); 
//print_r ($dir_matched); I tested this before return, both works fine. 

return array($files_matched,$dir_matched); 
} 



echo "<pre>"; 
list($a,$b) = getDirectory("F:\test"); 
print_r ($a); // this will result the same as array $files_matched, it ok! 
print_r ($b); // but i don't know why I cannot get the array of $dir_matched?? 
echo "</pre>"; 

실례로 볼 수 있듯이 하나의 배열 만 얻을 수 있다는 것이 이상합니다. 배열 $dir_matched의 내용을 가져올 수있는 아이디어가 있습니까?

+2

재귀 함수에서 재귀 호출이 전체 결과로 전파되는지 확인해야합니다. – JvdBerg

+1

왜 계속 같은 질문을합니까? 지난 번에 더 좋은 대안이 많이 있습니다 : http://stackoverflow.com/questions/13036110/how-to-get-recursive-filename-and-stored-it-into-array-in-php – mario

+0

이것은 모두 필요한 것입니다. : http://pastebin.com/Jixdq7JZ – Baba

답변

0

지금 작성된 방식대로 재귀 호출에서 값을 캡처하지 않습니다. 함수 내에서 다음 줄에 :

getDirectory("$path/$file", ($level+1)); 

반환 된 값을 캡처해야합니다. 뭔가 같은 :

$files_matched[++$i] = getDirectory("$path/$file", ($level+1)); 

$i 당신이 원하는, 당신은 또한 당신이 하위 디렉토리를 반영하기 위해 else statement에서 할, 그렇지 않으면 다른 변수를 캡처 좋아 여기를 증가해야하지 않을 수 있습니다 - 무엇에 따라 달라집니다 당신은 성취하기를 원합니다.

관련 문제