[英]Reading Multiple Files into a Single Array in 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);
?>
但是此代码的输出显示“ 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.