Search code examples
phparrayssearchflat-file

search within array for last 7 occurrences


I am writing a php code to search for different variables in a text file....

The data is listed line by line in a flatfile and the format for data listing is:

date | time | ip | geo-location (city) | //url

The data is saved as a logfile ('track-log.txt')

The code I have so far is:

$log_file = file_get_contents('track-log.txt');

$log_lines = explode(PHP_EOL, $log_file);

$log_lines = array_flip($log_lines);

unset($log_file);

this breaks down the text file into lines, then flips the lines backwards, so that they are listed in the array $log_lines[*] as last line in text file displayed first as $log_lines[0]

I need to count how many occurrences of "date" there are that are the same....

<..... lots of logs here .... then .....>

jan 1st 2012 | data.....
jan 1st 2012 | data ....
jan 1st 2012 | data ....
jan 1st 2012 | data ....
jan 1st 2012 | data ....
jan 2nd 2012 | data ....
jan 2nd 2012 | data ....
jan 2nd 2012 | data .... <end log>

Imagine this is the end of the log.... I would like:

$count[0] = 3 // last 3x dates are the same
$count[1] = 5 // the 5x dates before that are the same

So I can use

echo $count[0];

To display the amount of most recent values in the "date" part of the log.

I would like the array $count[*] to stop listing @ 7 strings....

$count[0]; ... up to ... $count[6]

Which will display the page counts of the last 7 days of logs

....

extra info.... the date format of each line in the logs is

sunday, january 22, 2012 | 16:14:36 | 82.**.***.*** | bolton | //page_url

And the date format is always the same as it is a script that writes each date on each log line

....


Solution

  • This should so the trick...

    <?php
    
    $log_file = file_get_contents('track-log.txt');
    $log_lines = explode(PHP_EOL, $log_file);
    $log_lines = array_reverse($log_lines);
    unset($log_file);
    $count = array();
    //loop through and itterate the count array using the date as the unique key
    foreach($log_lines as $line){
        //explode this so we can use the date segment as a key
        $pieces = explode('|',$line);
        if (!isset($count[$pieces[0]])){
            //break out if we've hit the cap size
            if (count($count)>=7){break;}
            $count[$pieces[0]] = 0; 
        }
        $count[$pieces[0]]++;
    
    }
    //switch to a numeric index
    $count = array_values($count);
    
    ?>