简体   繁体   中英

Delete csv lines in foreach

I have a large list, how do I for every loop in the foreach be excluded from the file 'list.csv' the line that passed through the foreach?

$myGetCsv = function ($str) {
    return str_getcsv($str, ';');
};    

$lines = array_map($myGetCsv, file(''.get_template_directory_uri() . '/list.csv'));     

foreach($lines as list($var1, $var2)) {
    //CODE
}

example:

original file:

test1, subtest1;  // test1 is $var1 and subtest1 is $var2
test2, subtest2;
test3, subtest3;

list.csv after the first foreach

test2, subtest2;
test3, subtest3;

list.csv after the second foreach

test3, subtest3;

list.csv after the third foreach

empty

Base on your clarifications in the comments it looks like the only reason why you are trying to delete the lines from the file is because you can't load the entire file in memory and want to parse the large file in multiple execution of the script.

If the above statement is accurate the short answer is that you do not have to load the entire file in memory.

You can use the class SplFileObject to iterate through the whole file one by one. Just make sure that within the loop you are NOT caching the rows in memory and are saving it to the new destination like a database.

Example:

$file = new SplFileObject('/path/to/file/list.csv');
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(';');

// Iterate through the whole file reading on line at a time
foreach ($file as $row) {
    list($var1, $var2) = $row;

    // Do what you want her but do not keep row info in memory
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM