php 使用特定变量计算文本文件中的行数

问题描述 投票:0回答:1

我有一个包含以下几行的文本文件

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
count
1个回答
0
投票

使用下面的

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
替换为您的文本文件名。

© www.soinside.com 2019 - 2024. All rights reserved.