Thursday, April 2, 2015

Convert CSV to Associative Array

function csvToAssocArray($csvFile) {
//This function will help you to convert any count of csv data in associative array
$row = 0;
$resultSet = array();
if (($handle = fopen($csvFile, "r")) !== FALSE) {
$dataCtr = 0;
$dataLabel = array();

while (($data = fgetcsv($handle, 10000, "\t")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if($row==0) $dataLabel[] = $data[$c]; //First row as heading as key for the associative array
else $resultSet[$row][$dataLabel[$c]] = $data[$c]; //other row to map the data with associative array
}
$row++;
}
fclose($handle);
} //End of while

return count($resultSet):$resultSet?false; //If no data return false;
}