PHP count line/row on text file based on value column

前端 未结 2 1201
慢半拍i
慢半拍i 2021-01-26 05:02

Continuing on my previous question.

I have text log file called reject. You can see it here

As you can see there are 4 steps on tab called:

1. Ba         


        
2条回答
  •  死守一世寂寞
    2021-01-26 05:36

    if you're ok with writing down your columns as keys then this should work as you described:

    $fromDateTime = new DateTime('Wed, Sep 19  2018 08:00:00');
    $toDateTime = new DateTime('Wed, Sep 19  2018 19:59:00');
    $file = file_get_contents('Reject.txt');
    $lines = explode("\n", $file);
    
    // counter
    $rowsintimespan = 0;
    // keys should correspond to columns
    $keys = [
        'date',
        'time',
        'battery',
        'piezo',
        'leftD3',
        'rightD2'
    ];
    
    $values = array_fill(0, count($keys), 0);
    $values = array_combine($keys, $values);
    
    // Do Line-By-Line starting by Line 16 (Array Index 15)
    for ($i = 11; $i < count($lines); $i++) {
        // if the file is "Tue, Sep 18201823:59:53"
        $dateobj = DateTime::createFromFormat("???,?M?d??Y?H:i:s+", $lines[$i]);
    
        // check if date is in your Timespan
        if ($dateobj < $toDateTime && $dateobj > $fromDateTime) {
            $rowsintimespan++; // count if in timespan
    
            // get line elements
            $lineContent = explode("\t", $lines[$i]);
    
            // loop through line elements and count them
            $x = 0;
            for ($j = 0; $j < count($keys); $j++) {
                if (!isset($lineContent[$j])) {
                    continue;
                }
    
                // remember position of last not empty column
                if (trim($lineContent[$j]) != '') {
                    $x = $j;
                }
            }
    
            if ($x > 0) {
                $values[$keys[$x]]++;
            }
        }
    }
    
    // Debug-Output
    echo $rowsintimespan;
    
    // Output every column
    echo '
    ';
    print_r($values);
    

    This will print out:

    Array
    (
        [date] => 0
        [time] => 0
        [battery] => 4
        [piezo] => 31
        [leftD3] => 17
        [rightD2] => 1
    )
    

提交回复
热议问题