[英]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. 请帮助我有关如何从目录中读取多个文件并将其合并到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. 但是此代码的输出显示“ Total Words:0”,尽管如此,我在目录中有两个文件,总共占了910个单词。
Regards, 问候,
Small mistake: 小错误:
$file_array=array_merge($file_array, $text);
Should be inside the if
block, not outside it. 应该在
if
块内部,而不是外部。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.