Creating a struct by looping

Posted on Wednesday, December 2nd, 2009 at 8:31 pm

On a regular basis I find myself needing to create a Coldfusion struct dynamically with a loop.  Although creating a struct in Coldfusion couldn’t be simpler or more intuitive (in my opinion), creating a struct dynamically is a little more problematic.  The problem is that you can’t set the name of your labels in your struct that holds your looped data dynamically.

So for example, let’s say that we want to create a struct that holds five sets of data labeled loop1 that is equal to loop_data_1, loop2 that is equal to loop_data_2, and so on up to loop 5.  When we dump our struct we want it to look like the following.

Dynamically created data in a struct

Dynamically created data in a struct

So let’s look at the code that we need to write to accomplish this.

<!— SET THE NUMBER OF LOOPS TO RUN —>
<cfset VARIABLES.loops = 5>

<!— CREATE A STRUCT —>
<cfset VARIABLES.data = structnew()>

<!— SET A VALUE INTO THE STRUCT.  THIS REPRESENTS HOW TO HARDCODE DATA INTO THE STRUCT —>
<cfset VARIABLES.data.working = true>

<!— RUN OUR LOOP —>
<cfloop from=”1″ to=”#VARIABLES.loops#” index=”VARIABLES.i”>

<!— SET DATA DYNAMICALLY INTO THE STRUCT —>
<cfset “VARIABLES.data.loops.loop#VARIABLES.i#” = “loop_data_” & VARIABLES.i>

</cfloop>

<!— DUMP OUR STRUCT —>
<cfdump var=”#VARIABLES.data#”>

Everything here is fairly straightforward up until we get to setting the data into the struct inside our loop.  What we need to do is set the label of our data to be “loop” and then whatever the current loop index is.  So if we are on our third loop our label will be “loop3″.  The problem is that you can just set a label by writing VARIABLES.data.loops.loop#VARIABLES.i#.  You’ll get yourself a nice little cf error something along the lines of:

Error thrown when creating a dynamically named struct label.

Error thrown when creating a dynamically named struct label.

To get around this all you need to do is wrap your label in quotation marks as is above in the code.  So VARIABLES.data.loops.loop#VARIABLES.i# becomes “VARIABLES.data.loops.loop#VARIABLES.i#”.  And that is it.  Your now able to create and label your struct dynamically.  To see how to output this data dynamically I’ve written another post on Dynamically Displaying Struct Data with a Loop.  Feel free to check it out as well.

2 Responses to “Creating a struct by looping”
  1. [...] pukkared Web Design & Development Creating a struct by looping [...]

  2. [...] other articles on just this topic.  You can review how to set data dynamically into a loop with Creating a Struct by Looping, and review how to output struct data dynamically with a loop with Dynamically Displaying Struct [...]

Leave a Reply

*
(Won't be published) *