Home > Mobile >  PHP: Find a string in a CSV, print it as well as a line X rows before it, and another line X rows af
PHP: Find a string in a CSV, print it as well as a line X rows before it, and another line X rows af

Time:04-06

I have a simple 275 /- line CSV file containing the dates a U.S. stock exchange is open, as well as the time of day at which it opens and closes. I'm only concerned with the date - which is at index position '0' of each line.

e.g.

2022-04-01,2022-04-01 13:30:00 00:00,2022-04-01 20:00:00 00:00

I can find and print the date that I'm looking for and I can use that to find the line numbers of the lines that are x lines prior and x lines after that (I'm using 14 days as an example in the code I included), but I don't know how to extract the dates from the latter two. Any help would be appreciated.

The code I'm using to search for a given date.

$lines = 'market_schedule.csv';
$date = '2022-04-01';

$row = 1;
if (($handle = fopen($lines, "r")) !== FALSE) {
    fgetcsv($handle, 1000, ",");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row  ;
        if(($data[0] == $date)){
            echo $data[0] . " is on line ".$row."<br />";
            // $prev = [$row - 14];
            // echo "Line " . $prev[0] . " is 14 lines prior.<br />";
            // $fut = [$row   14];
            // echo "Line " . $fut[0] . " is 14 lines after.<br />";
        }
    }
fclose($handle);
}

CodePudding user response:

As @Andrea mentioned - you'll need to read in the whole file into memory before you can do the checking you're after. Here is an example that assumes a lot, and could use some error checking and optimizing but could get you over this hurdle.

$lines = 'market_schedule.csv';
$date = '2022-04-01';

$matchedRow = 0;
$row = 1;
$allRows = [];
if (($handle = fopen($lines, "r")) !== FALSE) {
    fgetcsv($handle, 1000, ",");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row  ;
        $allRows[] = $data;

        if ($data[0] == $date){
            $matchedRow = $row;
        }   
    }
    fclose($handle);
}

$rowOffset = 14;
if ($matchedRow > 0) {
    echo $allRows[$matchedRow][0] . " is on line $matchedRow <br />";

    // You'll need to error check that $prev and $fut
    // are valid rows
    $prev = $matchedRow-$rowOffset;
    $fut = $matchedRow $rowOffset;
    
    echo "Line " . $allRows[$prev][0] . " is $rowOffset lines prior.<br />";
    echo "Line " . $allRows[$fut][0] . " is $rowOffset lines after.<br />";
} else {
    echo "Didn't find a date match.<br />";
}
  • Related