简体   繁体   English

fgetcsv 跳过 csv 文件中的空白列并给出偏移错误

[英]fgetcsv skip blank columns in csv file and gives Offset error

I have this script, it copies the data from file1 to newFile.我有这个脚本,它将数据从 file1 复制到 newFile。 And before copying it to new file, I fill out some empty columns using index (same for all rows) and it gives me an offset error.在将它复制到新文件之前,我使用索引(所有行都相同)填写了一些空列,它给了我一个偏移错误。

For ex, my file1.csv looks like this例如,我的 file1.csv 看起来像这样

aa,bb,cc,,ee,,, aa,bb,cc,,ee,,, aa,bb,cc,,ee,,, aa,bb,cc,,ee,,,

Output that I wish for is following我希望的输出如下

aa,bb,cc,abcd,ee,,, aa,bb,cc,abcd,ee,,, aa,bb,cc,abcd,ee,,, aa,bb,cc,abcd,ee,,,

Since 4th column is empty, (check file1.csv) fgetcsv only reads till cc , cuz it's empty after cc .由于第 4 列是空的,(检查 file1.csv) fgetcsv 只读取到cc ,因为它在cc之后是空的。 So ee got skipped.所以ee被跳过了。 So output that I get with Offset error is(newFile), also remaining commas and delimeter commas are gone.所以我得到的 Offset 错误输出是(newFile),剩余的逗号和分隔符逗号也消失了。

 aa bb cc abcd aa bb cc abcd aa bb cc abcd aa bb cc abcd

I want to create a newFile with all comma-separated values and with all remaining commas.我想用所有逗号分隔的值和所有剩余的逗号创建一个 newFile。 Let me know if you could help me in either way.如果您能以任何方式帮助我,请告诉我。

Here is my script这是我的脚本

//Open the old file for reading
$file1 = fopen("myfile2.csv", "r");
 
//Create a new file for writing
$newFile = fopen("$fname", "w+"); 

while (($row = fgetcsv($file1, 1000)) !== FALSE) {
    $var = "abcd";
    //insert at 3rd index
    $row[3]=$var;
    //write data into new file
    fputcsv($newFile, array_values($row), ','); 
}
fclose($file1);

You are outputting only the array_values() and only the first 4 occurances of that array have a value, hence it looks truncated.您只输出array_values()并且只有该数组的前 4 次出现才有值,因此它看起来被截断了。 I think the whole array_values() usage was incorrect, so output the $row array in fputcsv() as below我认为整个array_values()用法不正确,因此在fputcsv()输出$row数组如下

//Open the old file for reading
$file1 = fopen("myfile2.csv", "r");
 
//Create a new file for writing
$newFile = fopen("$fname", "w+"); 

while (($row = fgetcsv($file1, 1000)) !== FALSE) {
    $var = "abcd";
    //insert at 3rd index
    $row[3]=$var;
    //write data into new file
    fputcsv($newFile, $row);    // <- changed here
}
fclose($file1);

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

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