简体   繁体   English

在foreach中删除CSV行

[英]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? 我的清单很大,如何将foreach中的每个循环从文件“ list.csv”中排除通过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 第一个foreach之后的list.csv

test2, subtest2;
test3, subtest3;

list.csv after the second foreach 第二个foreach之后的list.csv

test3, subtest3;

list.csv after the third foreach 第三个foreach之后的list.csv

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. 您可以使用类SplFileObject遍历整个文件。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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