简体   繁体   中英

Reading Multiple Files into a Single Array in PHP

Please help me somebody as to how to read multiple files from a directory and merge them into a single array in PHP. I have developed a code but it does not work, as follows:

<?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);  
?>

But the output of this code indicates "Total Words: 0", notwithstanding, I have two files in the directory which account for 910 words collectively.

Regards,

Small mistake:

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

Should be inside the if block, not outside it. Rest of your code is fine. Like this

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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM