Skip to content

Instantly share code, notes, and snippets.

@ryumada
Last active February 7, 2021 01:52
Show Gist options
  • Save ryumada/01b02d3e738e096bbf1317311c66f064 to your computer and use it in GitHub Desktop.
Save ryumada/01b02d3e738e096bbf1317311c66f064 to your computer and use it in GitHub Desktop.
function to create an associative array from csv file using fgetcsv.
<?php
// add some classes or add this function to your class
public function convertToCsv(){
$file = fopen(base_url('mycsv.csv'), 'r'); // take file location
$arr = array(); $x = 0; $index = array(); // prepare variable for container and index
while (($line = fgetcsv($file)) !== FALSE) { // iteration on each line of csv
//$line is an array of the csv elements
if($x == 0){ // for the first line, use it as index
foreach($line as $k => $v){ // iterate the first line
$index[$k] = $v; // place it to index variable
}
$x++; // add flag
} else {
$y = 0; // for indexing line
foreach($index as $k => $v){ // iterate the index
$arr[$x-1][$v] = $line[$y];
$y++;
}
$x++;
}
}
fclose($file); // close the file
print_r($arr); // print array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment