2014-06-19 4 views
0

디렉토리에서 여러 파일을 읽고 PHP에서 단일 배열로 병합하는 방법에 대해 도움을주십시오.PHP에서 단일 배열로 여러 파일 읽기

<?php 
$directory = "archive/"; 
$dir = opendir($directory); 
$file_array = array(); 
while (($file = readdir($dir)) !== false) { 
    $filename = $directory . $file; 
    $type = filetype($filename); 
    if ($type == 'file') { 
    $contents = file_get_contents($filename); 
    $texts = preg_replace('/\s+/', ' ', $contents); 
     $texts = preg_replace('/[^A-Za-z0-9\-\n ]/', '', $texts); 
     $text = explode(" ", $texts); 
    } 
$file_array = array_merge($file_array, $text); 
} 
$total_count = count($file_array); 
echo "Total Words: " . $total_count; 
closedir($dir); 
?> 

그러나이 코드의 출력이 표시 "총 단어 : 0,"내가 공동으로 910 개 단어에 대한 계정 디렉토리에이 개 파일을 가지고에도 불구하고, 다음과 같이, 나는 코드를 개발했지만 작동하지 않습니다 .

감사합니다,

+0

'echo count ($ text)'는 무엇을 표시합니까? – Barmar

답변

1

작은 실수 :

$file_array=array_merge($file_array, $text); 

하지 그것을 외부에서 if 블록 안에 있어야합니다. 나머지 코드는 괜찮습니다. 이와 같이

if ($type == 'file') { 
    $contents = file_get_contents($filename); 
    $texts = preg_replace('/\s+/', ' ', $contents); 
    $texts = preg_replace('/[^A-Za-z0-9\-\n ]/', '', $texts); 
    $text = explode(" ", $texts); 
    $file_array = array_merge($file_array, $text); 
    } 
+0

편리한 답장을 보내 준 Hanky에게 감사드립니다. 그것은 내 문제를 해결했다. – ImranToor