Last active
January 28, 2024 22:06
-
-
Save illifw/de5d74e3b5d72ae46be67dc1bb90d96a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class TSV | |
{ | |
static function lines(string $file, callable $filter) | |
{ | |
$handle = null; | |
try | |
{ | |
if(false === ($handle = fopen($file, 'r'))) | |
return false; | |
$headers = null; | |
$line = 0; | |
while(false === feof($handle) | |
&& false !== ($data = fgets($handle)) | |
) | |
{ | |
if(null === $headers | |
&& 0x00 === $line) | |
{ | |
$headers = $data; | |
continue; | |
} | |
$line++; | |
if([null] === $data) | |
{ | |
continue; | |
} | |
$res = call_user_func_array( | |
$filter, | |
[ | |
$data, | |
$headers, | |
&$handle, | |
$line | |
] | |
); | |
if(false === $res) | |
continue; | |
yield $res; | |
} | |
fclose($handle); | |
$handle = null; | |
} | |
catch(Exception $e) | |
{ | |
trigger_error(__METHOD__.': '.$e->getMessage(), E_USER_NOTICE); | |
} | |
finally | |
{ | |
if(null !== $handle) | |
fclose($handle); | |
return false; | |
} | |
return true; | |
} | |
} | |
foreach(TSV::lines('H:\title.basics.tsv', function($data, $headers, $line, &$handle) | |
{ | |
if($data[0] === 'tt0000002' | |
|| $data[0] === 'tt0000003' | |
|| $data[0] === 'tt1000000' | |
) | |
{ | |
var_dump($line); | |
return (object) array_combine( | |
str_getcsv($headers, "\t"), | |
str_getcsv($data, "\t") | |
); | |
} | |
else return false; | |
}) as $data) | |
{ | |
var_dump($data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment