I went searching for a way to convert CSV to an Associative array, and I found old code in a couple places, but they were for AHK v1. So, because I needed this for work, I went about trying to recreate it for v2. The original code can be found here:
read CSV to Associative Array
What this does is allow you to turn a CSV file into an associative array in AHKv2 Enjoy!
Code: Select all
CSVprs(str) ;creates an array of the elements of a CSV string
{
arr := []
Loop Parse, str, "CSV"
arr.Push(A_LoopField)
return arr
}
CSVtoDict(file)
{
array := Map()
data := StrSplit(FileRead(file), "`n", "`r")
hdr := CSVprs(data.RemoveAt(1)) ;reads the 1st line into an array and deletes it from the data array. Remove this line if your data does not have Headers.
for x,y in data
{
array[x] := Map()
for k,v in CSVprs(y)
array[x][hdr[k]] := v ;change [hdr[k]] to just [k] if no headers
}
Return array
}
Code: Select all
/*
EXAMPLE DATA(SAVE THIS AS A CSV):
accountId, dealerName, dealerAddress, POCName, POCTN, POCEmail, DPMName, DPMEmail, DPMTN, accountType, DualPartner, engagement, advertising, 3pt, SEO, CustomHUD, MPRPrefType, Statisfaction, Group, Lat, Long, TimeZone, OEM, Contacts, Notes
"coolestdealerever", "Coolest Car Dealer Ever", "2300 marsh ln,dallas NM 75085", "1234567890", "Nathan Northcut", "1234567890", "noreply@noreply.com", "Courtney Douglas", "noreply@noreply.com", "1234567890", "Lincoln", , "Engaged", "Mix", "No", "No", "none", "Either", "Satisfied", "Retail", "29", "33", "America/Chicago", "Lincoln", "Lance Willis|noreply@noreply.com|,secondContact|noreply@noreply.com|1234567891", "this is just a set of notes here!"
*/
csvFilePath := FileSelect(1, , "Select the CSV file to import your accounts from", "*.csv")
if (csvFilePath != "") {
accountArray := CSVtoDict(csvFilePath)
MsgBox accountArray[1]["accountId"] . " | " . accountArray[1]["dealerName"] ;If no headers, then return the indices instead (e.g. accountArray[1][1], accountArray[1][2])
}