I am trying to load a CSV file into an array using ColdFusion (version 7.0.2.142559). Right now I am getting the following error:
A scalar value of type coldfusion.runtime.Struct cannot be assigned to a 2-dimensional ColdFusion array. A ColdFusion 2-dimensional array can only hold 1-dimensional ColdFusion arrays and Java List objects.
My CSV file is setup in this format:
a,b
c,d
e,f
This is my first go with ColdFusion so I probably have some simple syntax error that I just cannot see. Code is below.
<!--- get the current full path of the current --->
<cfset currentPath = getCurrentTemplatePath()>
<cfset currentDirectory = getDirectoryFromPath(currentPath)>
<!--- get and read the CSV-TXT file --->
<cffile action="read" file="#currentDirectory#/smalltest.csv" variable="csvfile">
<!--- create a new array --->
<cfset array=ArrayNew(2)>
<!--- loop through the CSV-TXT file on line breaks and insert into database --->
<cfloop index="index" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
<cfset array[#index#开发者_如何学Go][1]=#listgetAt('#index#',1, ',')#>
<cfset array[#index#][2]=#listgetAt('#index#',2, ',')#>
</cfloop>
<cfdump var=#array#>
Bonus:
On a side note it would save me a lot of time if there were some way to call upon a PHP file from within ColdFusion since I already have this entire script completed (this is just a small portion) in PHP. I read about ColdFusion custom tags (the tag <cf_php>
would work perfect for me) but admin says no, thus I must work with ColdFusion or find some way to render PHP through ColdFusion. Frames, JavaScript, or the <cfhttp>
tag are all things I think might work... if you have an idea let me know.
Actually I think you could simplify Henry's example even further using a one dimensional array and arrayAppend.
<cfset array=ArrayNew(1)>
<cfloop index="line" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
<cfset arrayAppend(array, listToArray(line))>
</cfloop>
A scalar value of type coldfusion.runtime.Struct cannot be assigned to a 2-dimensional ColdFusion array.
FYI: The original code is mixing loop types. With <cfloop list="..">
the index
value is an element of the list like "a,b" (not a line number). Obviously "a,b" is not the expected numeric index, hence the error.
<!--- what the code is actually doing --->
<cfset array['a,b'][1]=#listgetAt('#index#',1, ',')#>
<cfset array['a,b'][2]=#listgetAt('#index#',2, ',')#>
<cfset array['c,d'][1]=#listgetAt('#index#',1, ',')#>
....
Having nothing to do with your error, none of those # signs are necessary. The code will work either way, but it is cleaner to write:
<cfset array[lineNum][1]= listgetAt( index, 1, ',')>
instead of
<cfset array['#lineNum#'][1]=#listgetAt('#index#',1, ',')#>
<cfset array=ArrayNew(2)>
<cfset lineNum=1>
<cfloop index="line" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
<cfset array[lineNum] = listToArray(line)>
<cfset lineNum = lineNum + 1>
</cfloop>
精彩评论