Hello. There is a txt file that contains many lines. I bring this file to the page, breaking into lines. After that, I select only those rows, elements of the array, which consist of 20 elements. I take the first and second word (this is the date and time) from each line. And it turns out something like:

2018/01/15 15:00:00 2018/01/15 15:00:00 2018/01/15 16:00:00 2018/01/15 18:00:00 2018/01/15 18:00:00 

I need to get only lines with different dates at the output:

 2018/01/15 15:00:00 2018/01/15 16:00:00 2018/01/15 18:00:00 $log = file_get_contents('./file.txt', FILE_USE_INCLUDE_PATH); $line = explode("\n", $log); foreach ($line as &$value_line) { $arr_line = explode(' ', $value_line); if (count($arr_line) == 20) { $dateTime = $arr_line[0]." ".$arr_line[1]; echo $dateTime; echo "<hr>"; } } 

How can I do it?

  • I suppose you can use for instead of foreach - Akubik
  • one
    Get a variable in which you will store the previous date. and compare with it. type if($old != $dateTime) { echo "$dateTime<hr>"; } $old=$dateTime; if($old != $dateTime) { echo "$dateTime<hr>"; } $old=$dateTime; - Mike
  • or print the strings if (strcmp($dateTime; $arr_line[0]." ".$arr_line[1])) - Akubik
  • @Denis and the lines are sorted at the entrance? - splash58

1 answer 1

It is necessary to enter an auxiliary variable, for example an array:

 $datas = array(); foreach ($line as &$value_line) { $arr_line = explode(' ', $value_line); if (count($arr_line) == 20) { $dateTime = $arr_line[0]." ".$arr_line[1]; if( !in_array( $dateTime , $datas) ){ $datas[] = $dateTime; echo $dateTime; echo "<hr>"; } } } 

Or a string:

 $before = ''; foreach ($line as &$value_line) { $arr_line = explode(' ', $value_line); if (count($arr_line) == 20) { $dateTime = $arr_line[0]." ".$arr_line[1]; if( $dateTime != $before ){ $before = $dateTime; echo $dateTime; echo "<hr>"; } } } 

But the line if the same dates go only in a row

  • yes, the variable and so is $dateTime it stores the last element, but to work in any case, and not just for adjacent lines, then .. save each output line to an array and output the next line if there is no line in the array. add brute force in this array through additional foreach .. but in the question indicated that the rows are sorted, then the cycle is not needed - Akubik