0

The following code is what I am using to get an entire column of data from my csv files. (There are many columns, but I only need #2). This code will put all of the data into the array called $cbsmin. What I need to do is skip the very first piece of data in each file as it is the category name not actually a piece of data.

How would this best be done?

for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

            $cbsmin[] = $data[2];

        }
        fclose($handle);
    }
}

3 Answers 3

2

Just use a simple flag to mark if it is the first line. If it is, reset the flag to false and skip that line.

$isfirst = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($isfirst)
    {
        $isfirst = false;
        continue;
    }
    $cbsmin[] = $data[2];
}
Sign up to request clarification or add additional context in comments.

Comments

2

Just execute a single

   fgetcsv($handle, 1000, ",");

before the while loop.

1 Comment

Yes, this would be a better solution rather than writing this much piece of code. Why write extra lines if you get the desired solution by writing only just one line.
0

Just throw in an extra read prior to going into the while loop

for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        // eat the header
        fgetcsv($handle, 1000, ",");
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

            $cbsmin[] = $data[2];

        }
        fclose($handle);
    }
}

Another technique I use for this is to use the header row for keys in the data. This works if the header rows are consistent over time and from file to file.

for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        // eat the header
        $header = fgetcsv($handle, 1000, ",");
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $data = array_combine($header, $data);
            $cbsmin[] = $data["Customer Name"];

        }
        fclose($handle);
    }
} 

It beats having to use field offsets if you are doing anything non-trivial with a lot of the fields.

Comments

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.