-
-
Save KarelWintersky/1a2cb0bbfd0a1fe244f7 to your computer and use it in GitHub Desktop.
Convert a comma separated file into an associated 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
/** | |
* Convert a comma separated file into an associated array. | |
* The first row must contain the array keys. | |
* Return something like this: | |
* Array | |
( | |
[0] => Array | |
( | |
[name] => Lorem | |
[number] => 11 | |
) | |
[1] => Array | |
( | |
[name] => ipsum | |
[number] => 22 | |
) | |
) | |
* | |
* | |
* @param string $filename Path to the CSV file | |
* @param string $delimiter The separator used in the file (default `,`) | |
* @param string $enclosure The enclosure used in the file (default `"`) | |
* @return array|bool | |
* | |
* @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 | |
*/ | |
function csv_to_array($filename='', $delimiter=',', $enclosure = '"') { | |
ini_set('auto_detect_line_endings',TRUE); | |
if(!file_exists($filename) || !is_readable($filename)) | |
return FALSE; | |
$header = NULL; | |
$data = array(); | |
if (($handle = fopen($filename, 'r')) !== FALSE) | |
{ | |
while (($row = fgetcsv($handle, 1000, $delimiter, $enclosure)) !== FALSE) | |
{ | |
if (!$header) { | |
$header = $row; | |
} | |
else { | |
if (count($header) > count($row)) { | |
$difference = count($header) - count($row); | |
for ($i = 1; $i <= $difference; $i++) { | |
$row[count($row) + 1] = $delimiter; | |
} | |
} | |
$data[] = array_combine($header, $row); | |
} | |
} | |
fclose($handle); | |
} | |
return $data; | |
} |
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
name | number | |
---|---|---|
Lorem | 11 | |
ipsum | 22 |
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
Array | |
( | |
[0] => Array | |
( | |
[name] => Lorem | |
[number] => 11 | |
) | |
[1] => Array | |
( | |
[name] => ipsum | |
[number] => 22 | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment