请帮助我了解如何从一个目录中读取多个文件,并将它们合并到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);
?>
但该代码的输出指示"Total Words: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);
}