Created
November 6, 2017 18:49
-
-
Save landsman/ce658e3ee0f69bdee8112101ac1757d9 to your computer and use it in GitHub Desktop.
CSV to associative array
This file contains hidden or 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 | |
| class RandomClass | |
| { | |
| /** | |
| * Convert a comma separated file into an associated array. | |
| * The first row should contain the array keys. | |
| * | |
| * Example: | |
| * | |
| * @param string $filename Path to the CSV file | |
| * @param string $delimiter The separator used in the file | |
| * @return array | |
| * @link http://gist.github.com/385876 | |
| * @author Jay Williams <http://myd3.com/> | |
| * @copyright Copyright (c) 2010, Jay Williams | |
| * @license http://www.opensource.org/licenses/mit-license.php MIT License | |
| */ | |
| private function csvToArray($filename='', $delimiter=',') | |
| { | |
| if(!file_exists($filename) || !is_readable($filename)) | |
| return FALSE; | |
| $header = NULL; | |
| $data = []; | |
| if (($handle = fopen($filename, 'r')) !== FALSE) | |
| { | |
| while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) | |
| { | |
| if(!$header) | |
| $header = $row; | |
| else | |
| $data[] = array_combine($header, $row); | |
| } | |
| fclose($handle); | |
| } | |
| return $data; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment