Created
November 22, 2011 18:50
-
-
Save billhance/1386513 to your computer and use it in GitHub Desktop.
CSV to Array function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function csv_to_array($csv,$has_headings=false,$delimiter=',',$enclosure='"',$escape="//",$eol="\n") | |
{ | |
$headings = null; | |
$data = array(); | |
$csv = str_getcsv($csv, $eol); // Array containing each line | |
if(empty($csv[0])) | |
{ | |
return array(); | |
} | |
if($has_headings) | |
{ | |
$headings = str_getcsv($csv[0], $delimiter, $enclosure, $escape); | |
array_shift($csv); // Remove the heading row and reset keys | |
} | |
$count = count($csv); | |
for($i = 0; $i < $count; $i++) | |
{ | |
$data[$i] = str_getcsv($csv[$i], $delimiter, $enclosure, $escape); | |
if(isset($headings)) | |
{ | |
$data[$i] = array_combine($headings, $data[$i]); | |
} | |
} | |
return $data; | |
} | |
$csv = <<<EOD | |
"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE" | |
"1985/01/21","Douglas Adams",0345391802,5.95 | |
"1990/01/12","Douglas Hofstadter",0465026567,9.95 | |
"1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99 | |
"1999/12/03","Richard Friedman",0060630353,5.95 | |
"2001/09/19","Karen Armstrong",0345384563,9.95 | |
"2002/06/23","David Jones",0198504691,9.95 | |
"2002/06/23","Julian Jaynes",0618057072,12.50 | |
"2003/09/30","Scott Adams",0740721909,4.95 | |
"2004/10/04","Benjamin Radcliff",0804818088,4.95 | |
"2004/10/04","Randel Helms",0879755725,4.50 | |
EOD; | |
$arr = csv_to_array($csv,true); | |
print_r($arr); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment