0

我有一个将字符串附加到文件末尾的 PHP 脚本。然后我希望能够读取该文件并找出每行出现的次数,然后计算最常出现的行和它们的数字。例如,如果我有:

williamtdr
chicken
chicken
williamtdr
williamtdr
pig

我会得到:

williamtdr, 3
chicken, 2
pig, 1

有没有办法在 PHP 中做到这一点?

谢谢!

4

2 回答 2

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
)

[演示]


如果您想要与您的问题相同的输出,您可以像这样循环它:

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-10T00:21:32.700 回答
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);
于 2013-05-10T00:28:42.553 回答