[英]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.