Last active
August 29, 2015 14:19
-
-
Save shlomohass/2bb864e34eae4930d809 to your computer and use it in GitHub Desktop.
PHP Easy Clean An Quick .CSV Import into Array
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 | |
/* | |
Parse CSV into an array: | |
*/ | |
$csv = array_map('str_getcsv', file('csvfile.csv')); | |
/* | |
* OUTPUT: | |
* Array( | |
* [0] => Array([0] => NAME, [1] => CLASS, [2] => ROOM), | |
* [1] => Array([0] => Sally, [1] => 2018, [2] => 312), | |
* [2] => Array([0] => Belinda, [1] => 2017, [2] => 148) | |
* ) | |
*/ | |
/* | |
* Parse CSV into an associative array : | |
* | |
* METHOD 1: | |
*/ | |
function assoc_getcsv($csv_path) { | |
$r = array_map('str_getcsv', file($csv_path)); | |
foreach( $r as $k => $d ) { $r[$k] = array_combine($r[0], $r[$k]); } | |
return array_values(array_slice($r,1)); | |
} | |
/* | |
* Parse CSV into an associative array : | |
* | |
* METHOD 2: | |
*/ | |
function assoc_getcsv($csv_path) { | |
$f = array(); | |
function parse_csv_assoc($str,&$f){ | |
if (empty($f)) { $f = str_getcsv($str); } | |
return array_combine($f, str_getcsv($str)); | |
} | |
return array_values(array_slice(array_map('parse_csv_assoc', file($csv_path), $f),1)); | |
} | |
/* OUTPUT: | |
* | |
* Array( | |
* [0] => Array([NAME] => Sally, [CLASS] => 2018, [ROOM] => 312), | |
* [1] => Array([NAME] => Belinda, [CLASS] => 2017, [ROOM] => 148) | |
* ) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment