0
votes

Can anybody explain how to make associative array from CSV file in ColdFusion. I have implemented this in PHP but needed now in ColdFusion as well. I have first row as header and want to use them as keys and all rows from CSV except the first one as value in assoc array.

Please let me know what you need further. Help would be appreciated.

3
Sorry . I meant first row. Thank you - U.Malik
Just for completeness, an "associative array" in ColdFusion is called a "structure". - Shawn

3 Answers

4
votes

If you read the file with the <cfhttp> tag, and include a name attribute, you will have a ColdFusion query object at your disposal. While this is not called an associative array, it effectively is one.

Code samples and a more detailed explanation are available here. https://www.bennadel.com/blog/1903-parsing-csv-data-with-coldfusion-s-cfhttp-tag.htm

1
votes

As others have already said, you can easily convert a CSV file into a query object using cfhttp. Also, since you're using ColdFusion 11, you can convert a query object into json using serializeJson with the struct option. Then deserializeJson to convert it back into an array of structs. All you need is 2 lines of code and your done.

See code example and link to TryCF gist below.

https://trycf.com/gist/b8f30141e8e6b588a396fb1051a38447/acf11?theme=monokai

<cfscript>
    cfhttp( 
        name="myData", 
        url="https://raw.githubusercontent.com/sauravg94/test-repo/master/MOCK_DATA.csv", 
        firstrowasheaders="true",
        method="GET"
    );
    myArrayOfStructs = deserializeJson(serializeJson(myData, "struct"));

    writedump(myData);
    writeDump(myArrayOfStructs);

</cfscript>

EDIT

Code updated due to Dan Bracuk's comment where he pointed out that I did not answer the question that was asked.