Skip to main content
Known Participant
March 23, 2010
Answered

Accessing Structure within an Array

  • March 23, 2010
  • 3 replies
  • 5045 views

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

The value coldfusion.runtime.Struct cannot be converted to a number.

<cfoutput>#date_examples.date#</cfoutput>

This topic has been closed for replies.
Correct answer BKBK

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>

3 replies

ilssac
Inspiring
March 23, 2010

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>

flhtflhtAuthor
Known Participant
March 23, 2010

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!

ilssac
Inspiring
March 23, 2010

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.

BKBK
Community Expert
BKBKCommunity ExpertCorrect answer
Community Expert
March 23, 2010

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>

flhtflhtAuthor
Known Participant
March 23, 2010

I got it, changed cfloop to

<cfloop

from="1" to="#ArrayLen(date_examples)#" index="i">