Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中将多个文件读入单个数组_Php_File Io - Fatal编程技术网

在PHP中将多个文件读入单个数组

在PHP中将多个文件读入单个数组,php,file-io,Php,File Io,请帮助我了解如何从一个目录中读取多个文件,并将它们合并到PHP中的单个数组中。我已经开发了一个代码,但它不起作用,如下所示: <?php $directory = "archive/"; $dir = opendir($directory); $file_array = array(); while (($file = readdir($dir)) !== false) { $filename = $directory . $file; $type = filetype($fil

请帮助我了解如何从一个目录中读取多个文件,并将它们合并到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);  
?>

但是这段代码的输出显示“totalwords:0”,尽管如此,我在目录中有两个文件,总共占910个单词

关于,

小错误:

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

echo count($text)
显示了什么?感谢您方便的回复。它解决了我的问题。