我有一个PHP脚本,它将一个字符串附加到文件的末尾。我希望能够读取该文件并找出每行发生的次数,然后计算最常出现的行和他们的数字。例如,如果我有:
williamtdr
chicken
chicken
williamtdr
williamtdr
pig
我会得到:
williamtdr, 3
chicken, 2
pig, 1
有没有办法在PHP中执行此操作?
谢谢!
答案 0 :(得分:4)
//$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);
答案 1 :(得分:0)
你将如何在现实生活中做到这一点?
您将打开该文件,然后开始计数:
$file = file('file.txt');
$counts = array();
foreach ($file as $line) {
$line = trim($line);
if ( ! isset($counts[$line]) {
$counts[$line] = 1;
} else {
$counts[$line]++;
}
}
var_dump($counts);