Ank
Ank

Reputation: 6270

Creating an associative array from a csv file php

I'm trying to read a csv file and then store the first and the 21st column in an associative array such that the 1st column becomes the key and 21st column becomes the value.

Later I would want to pull records based on the "key". The PHP file containing the code is upload.php

$calls = array();
$file_handle = fopen($C1.".File.csv","r"); // $C1 is defined before.
 //Just appending something to the file name. This file exists. 
while (!feof($file_handle) ) {
    $line= fgetcsv($file_handle, 1024);
    $calls[$line[0]] = $line[20]; //Line 94 of this file

}
fclose($file_handle);
print_r($calls);

I get this error

Undefined offset: 20 in upload.php on line 94

Where am I going wrong.

Upvotes: 0

Views: 563

Answers (1)

Emissary
Emissary

Reputation: 10148

The twentieth "column" in a zero-indexed array would be $line[19]

update as per your comment (and subsequent edit):

The error is clearly pointing out at some point during the loop $line[20] is not set - If each line has a suitable number of columns then the only other reason I can think of is that there is an empty line at the end of the CSV file.

Eg.

1.  foo, bar, baz
2.  a  , b  , c
3.                    <-- empty line as a result of carriage return

so... you want to check that trim($line)!='' before fgetcsv and/or as part of good error-handling check that the array's length is greater than the highest index you are trying to read.

Upvotes: 1

Related Questions