Created
March 2, 2020 11:00
-
-
Save MadMikeyB/981dd6ea46f8250d8024f1a5f13fecd5 to your computer and use it in GitHub Desktop.
Create an array from a CSV with headers as array keys.
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 | |
if ( (isset($_POST['submit'])) && (!empty($_POST['submit'])) && (! empty($_FILES['csv_upload']['name'])) ): | |
/** | |
* Map CSV items to rows. | |
* @see php.net/array_map | |
* @see php.net/file | |
*/ | |
$rows = array_map('str_getcsv', file($_FILES['csv_upload']['tmp_name'])); | |
/** | |
* Map CSV headers to keys. (while simultaneously stripping them from our $rows array) | |
* @see php.net/array_shift | |
*/ | |
$keys = array_shift($rows); | |
// Create a collection. | |
$collection = []; | |
// Create a data mapper. | |
$dataMapper = []; | |
// Start by looping through keys and: | |
// - Create a Data Map for Indeces to Keys | |
foreach ($keys as $index => $key): | |
// make the key a bit more machine readable. | |
$safeKey = strtolower(str_replace(' ', '_', $key)); | |
// remove anything in brackets. | |
$safeKey = str_replace('_(kg/g)', '', $safeKey); | |
// Push to dataMapper. | |
$dataMapper[$index] = $safeKey; | |
endforeach; | |
// Loop through the rows (which don't have keys any more..). | |
foreach ($rows as $row): | |
/** | |
* Combine the Data Mapper with the Row | |
* @see php.net/array_combine | |
*/ | |
if (count($dataMapper) === count($row)): | |
// Create Item with Keys and Values | |
$item = array_combine($dataMapper, $row); | |
// Push to our Users Collection | |
array_push($collection, $item); | |
endif; | |
endforeach; | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment