1

i have a small issue converting a csv file,

The file is converting, but is getting a Notice

Notice: Undefined offset: 2 in Notice: Undefined offset: 4 in

Also i need to group by $row[2] is this possible?

<?php

$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");

$file = fopen('file2.csv', 'w');
$header = array('col1', 'col2');
fputcsv($file, $header, ',', '"');

foreach ($tsvFile as $line => $row) {
    if($line > 0) {
        fputcsv($file, array($row[2], $row[4]), ',', '"');
    }
}
fclose($file);

?>

Any help is appreciated.

2
  • isset() is usually what you need when referencing an array offset that might not be set. The explode on the tabs might be getting munged on some rows or something... missing tabs or what not. Commented Mar 8, 2013 at 16:50
  • can you please explain more?, thanks Commented Mar 8, 2013 at 16:54

1 Answer 1

1

What if some rows have 4 values (columns) when delimited but others only have 1? Your code assumes a fixed number of $row[] elements. If you do isset($row[2]) and it returns false then you know you should not try and access it, which is what causes the notice.

As for why there is no value assigned to that offset I can't say without seeing the CSV. I've found commas work better than tabs as a delimiter - maybe you have too :)

Not fully sure I know what you mean by 'group by'. You could easily add a running total inside the foreach, or keep a count in another array using one of the columns as a dimension, with the total per dimension.

Sign up to request clarification or add additional context in comments.

7 Comments

I understand, but doing that is not changing the notice. Thanks allot
Maybe try fgetcsv instead. Or debug the foreach ($tsvFile as $line => $row). Use var_dump are $line and $row what you expect? I am guessing not.
I see now why is returning offset, is because at the end of the file is a blank line.
That would do it... if($line > 0) { is probably not what you want. I think what I said about using isset is still applicable. Basically you should not make an assumption that an offset exists unless you explicitly set it. Anyway, glad you got it sorted.
Group by i mean, i have 2 columns, code and qty, and the code is repeating, and i need to keep only a unic code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.