[thelist] nesting structures in ColdFusion

.jeff jeff at members.evolt.org
Thu Jul 12 21:51:48 CDT 2001


steve,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: Steve Lewis
:
: I am a php/mysql weenie who is learning
: ColdFusion now, and I made the mistake of
: assuming that nested structures could be
: interated through using cfloop the way you
: can in most other languages I know...
:
: [begin broken example]
: <cfset mystruct = StructNew()>
:   <cfset mystruct.sub1 = StructNew()>
:     <cfset mystruct.sub1.name = "name_1">
:     <cfset mystruct.sub1.favcolor = "color_1">
:   <cfset mystruct.sub2 = StructNew()>
:     <cfset mystruct.sub2.name = "name_2">
:     <cfset mystruct.sub2.favcolor = "color_2">
:
: <cfloop collection="#mystruct#" item="curritem">
:   <cfoutput>
:     #curritem.name#'s favorite color is
:     #curritem.favcolor#<br>
:   </cfoutput>
: </cfloop>
: [end broken example]
:
: This does not work because #curritem# is a string
: containing the value of the key, not the value
: itself, and not a pointer to the value, and not
: an object reference... three things I am accostomed
: to dealing with.  Why does it treat curritem as a
: string?  I dont like it, but dem's tuff luck.
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

it's a string representing the name of the current key actually.  using
bracket notation, you can get the value of that key within the structure:

#mystruct[curritem]#

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: #Evaluate(thecollection&'.'&newitem)#
:
: Now my problem is that this feels like a
: *hack* to me as I have personal issues with
: the evaluate() function...
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

yeah, i have personal issues with it as well -- yuck.

as a sidenote, i have issues with nesting a cfoutput inside of a cfloop, or
two cfloops as in this example.  i've run tests that show it's marginally
more efficient to wrap the loops with the cfoutput and not the other way
around, not to mention the improvement in readability when you do that.

see my answer above on how to access the key of a structure without using
the Evaluate() function.

since you have nested structures, you'll get an error if you try to access
the key of a struct whose value is itself another struct.  so, you'll need
to test for whether or not the value is a struct or not and perform another
loop collection if it is.

<cfoutput>
<cfloop collection="#mystruct#" item="sub">
  <cfif IsStruct(mystruct[sub])>
    <cfloop collection="#mystruct[sub]#" item="property">
      mystruct.#sub#.#property# = #mystruct[sub][property]#<br>
    </cfloop>
  </cfif>
</cfloop>
</cfoutput>

that should do it for ya.

good luck,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/






More information about the thelist mailing list