Skip to main content
Known Participant
January 4, 2008
Question

last element in structure

  • January 4, 2008
  • 2 replies
  • 1037 views
hey all-

i am trying to add a comma if this is last element in structure:

<cfset stuff=structnew()>
<cfset stuff.first=1>
<cfset stuff.first_first=2>
<cfset stuff.first_first_first=3>
<cfset stuff.first_first_first_first=4>
<cfset stuff.first_first_first_first_first=5>

<cfdump var="#stuff#">

<cfoutput>
<cfloop collection="#stuff#" item="i">
'#stuff #'<cfif StructCount(stuff) lt 6>,</cfif>
</cfloop>
</cfoutput>

but it is not workin. how do i get the last element.
    This topic has been closed for replies.

    2 replies

    Inspiring
    January 4, 2008
    As Adam said structures are unordered and there is no concept of last.
    But it looks like you are trying to output a list of elements by looping
    over the structure and do not want a comma after the last element. Your
    if logic is the problem here, it will always be true.

    <cfoutput>
    <cfloop collection="#stuff#" item="i">
    '#stuff #'<cfif StructCount(stuff) lt 6>,</cfif>
    </cfloop>
    </cfoutput>

    StructCount(stuff) is always five. It the size of the structure is not
    going to change while you are looping over it. You need a counter and
    then compare that counter to the size of the structure to know you have
    reached the end of it.

    <cfoutput>
    <cfset counter = 0>
    <cfloop collection="#stuff#" item="i">
    <cfset counter = counter + 1>
    '#stuff
    #'<cfif counter lt StructCount(stuff)>,</cfif>
    </cfloop>
    </cfoutput>

    This could be simplified with a list function.

    <cfset stuffList = ''>
    <cfloop collection="#stuff#" item="i">
    <cfset stuffList = listAppend(stuffList,stuff )>
    </cfloop>
    <cfoutput>#stuffList#</cfoutput>



    Inspiring
    January 4, 2008
    Structs are intrinsically unordered, so there's - also intrinsically - no
    "last" element.

    To implement ordering in a struct, you will need to do something like
    include an additional "index" key which stores ordering information. This
    could be a list or array of keys, in the ordering that you want
    (alphabetical, chronological, etc).

    structKeyList() and structKeyArray() *coincidentally* return a struct's
    keys alphabetically, so one could use one of those to generate an index.
    But, like I said, it's just a coincidence that they return the keys sorted.

    If your data is inately ordered, you probably should be using an array, not
    a struct (that's the whole difference between the two, really).

    --
    Adam