我有一个包含以下几行的文本文件
08/09/2023 19
08/09/2023 19
08/09/2023 19
08/09/2023 19
08/09/2023 19
09/09/2023 19
09/09/2023 19
09/09/2023 19
09/09/2023 19
10/09/2023 19
11/09/2023 20
15/09/2023 20
18/09/2023 20
21/09/2023 20
我想打印每个类别的总计,如下
Total for category 19 = 10
Total for category 20 = 4
使用下面的
PHP
代码来使用您的文件获得所需的输出:
<?php
// Initialize counters for each category
$category_19_count = 0;
$category_20_count = 0;
// Open and read the text file
$file = fopen('file.txt', 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
$parts = explode(' ', trim($line)); // Split the line into parts based on spaces and trim extra spaces
if (count($parts) === 2) {
$category = intval($parts[1]); // Get the second part as an integer
if ($category === 19) {
$category_19_count++;
} elseif ($category === 20) {
$category_20_count++;
}
}
}
fclose($file);
// Print the totals for each category
echo "Total for category 19 = $category_19_count\n";
echo "Total for category 20 = $category_20_count\n";
} else {
echo "Failed to open the file.";
}
?>
在上面的代码中,将
file.txt
替换为您的文本文件名。