2 回答

TA貢獻1816條經驗 獲得超4個贊
對于每個文件:讀取它,檢索第 7 行,用逗號分隔該行,對于該行中的每個字符串,將其添加到唯一鍵數組中,使用該字符串作為數組鍵。
$unique_tags = [];
foreach ( glob("data/articles/*.txt") as $file ) {
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tags = explode( ',', $lines[7] ); // 7th line is the tag line. Put all the tags in an array
// Process each tag:
foreach ( $tags as $key ) {
$unique_tags[ $key ] = $key;
}
}
那時,$unique_tags將包含所有唯一鍵(作為鍵和值)。

TA貢獻1809條經驗 獲得超8個贊
根據上面的答案,另一種選擇是使用array_count_values。在這種情況下,數組的所有鍵都是唯一的,但它還會計算數組中出現的鍵數:
$files = glob("data/articles/*.txt");
foreach($files as $file) { // Loop the files in the directory
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tags = explode( ',', strtolower($lines[7]) ); // 7th line is the tag line. Put all the tags in an array
// Process each tag:
foreach ($tags as $key) {
$all_tags[] = $key; // array with all tags
//$unique_tags[$key] = $key; // array with unique tags
}
}
$count_tags = array_count_values($all_tags);
foreach($count_tags as $key => $val) {
echo $key.'('.$val.')<br />';
}
您的輸出將類似于:
aaa(2) // 2 keys found with aaa
bbb(2) // 2 keys found with bbb
ccc(2) // 2 keys found with ccc
- 2 回答
- 0 關注
- 221 瀏覽
添加回答
舉報