请帮助我解释如何从目录中读取多个文件并将它们合并到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);
?>
但是这段代码的输出表示&#34;总词数:0&#34;尽管如此,我在目录中有两个文件,共有910个单词。
此致
答案 0 :(得分: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);
}