//$data = file_get_contents('yourfile.txt'); // get file contents
$data = 'williamtdr
chicken
chicken
williamtdr
williamtdr
pig';
$data = explode("\n", $data); // split data at each newline
$data = array_count_values($data); // count occurrences of each line
print_r($data);
將輸出:
Array
(
[williamtdr] => 3
[chicken] => 2
[pig] => 1
)
[DEMO]
如果你想在相同的輸出你的問題,你會遍歷它像這樣:
foreach ($data as $word => $count)
{
echo $word . ', ' . $count . "\n";
}
或者,更好的辦法是這樣做:
$data = file('yourfile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$data = array_count_values($data);
你嘗試過什麼嗎? – 2013-05-10 00:17:11
'str_word_count()'可能是一個好的開始,可能與'array_count_values()'相結合。 – kapa 2013-05-10 00:18:51