Copy link to clipboard
Copied
Hi,
What is the correct syntax for accessing a Structure within an Array.
Array Creation
<cfset date_examples = ArrayNew(1)>
<cfset date_example = {date=Application.start, mask="mm/dd/yyyy"}>
<cfset date_examples[1] = date_example>
Attempted Output
<cfloop
index="i" array="#date_examples#">
<cfoutput>#date_examples.date#</cfoutput>
<cfoutput>#date_examples.mask#</cfoutput>
</cfloop>
Error
<cfoutput>#date_examples.date#</cfoutput>
In this construction, the index i is an element of the array, hence a struct
<cfloop index="i" array="#date_examples#">
</cfloop>
What you apparently need is:
<cfloop index="i" from="1" to="#arrayLen(date_examples)#">
<cfoutput>#date_examples.date#</cfoutput><br>
<cfoutput>#date_examples.mask#</cfoutput>
</cfloop>
Copy link to clipboard
Copied
I got it, changed cfloop to
<cfloop
from="1" to="#ArrayLen(date_examples)#" index="i">
Copy link to clipboard
Copied
In this construction, the index i is an element of the array, hence a struct
<cfloop index="i" array="#date_examples#">
</cfloop>
What you apparently need is:
<cfloop index="i" from="1" to="#arrayLen(date_examples)#">
<cfoutput>#date_examples.date#</cfoutput><br>
<cfoutput>#date_examples.mask#</cfoutput>
</cfloop>
Copy link to clipboard
Copied
OR instead of useing the oldschool from to loop you could have contineued to use the newer array loop but just realizing that the itteration variable i was the array element not just an index to it.
I.E.
<cfloop index="i" array="#date_examples#">
<cfoutput>#i.date#</cfoutput>
<cfoutput>#i.mask#</cfoutput>
</cfloop>
Copy link to clipboard
Copied
Thanks Ian!
I didn't know you could do that.
I is the index AND each iterated array element, leaving out the from and to variables because cfloop is smart enough to figure that out.
You rock dude!
Copy link to clipboard
Copied
flhtflht wrote:
I is the index AND each iterated array element, leaving out the from and to variables because cfloop is smart enough to figure that out.
You rock dude!
Well it would be more accurate to say that the itteration varaible ("i" in your example) will be a variety of data types depending on the type of <cfloop...> it is in.
In the array loop it is each element of the array.
In a collection loop (i.e. structure) it is the name of the each structure key.
In a file loop it is one line of the file.
In a from to loop it is the current integer
etc.
So one should always understand what type of loop one is using.
Copy link to clipboard
Copied
That makes cfloop even smarter!