coldfusioncoldfusion-9coldfusion-10coldfusion-11coldfusion-2016

Get array key and structure data from an array with structure


I've got an array that has a structure. Problem is that I can't output the array number and the structure data in the same loop, but if I have two different loops, the data will show without any errors.

The code below has two different loops showing how I can access the array number and structure data separately.

How do you output the array number and structure data in the same loop?

Code can be tested here https://cffiddle.org/

<!--- Create new structure --->
<cfset structRe = StructNew() />

<!--- Add data to structure --->
<cfset structRe.id = "14">          
<cfset structRe.title = "Title">

<!--- Create new Array --->
<cfset arryRe = ArrayNew(1) />

<!--- Add structure to array --->
<cfset ArrayAppend(arryRe, structRe)>

<cfoutput>
    <cfdump var="#arryRe#" />
</cfoutput>

<!--- Loop to access structure --->
<cfloop array ="#arryRe#" index="i">

    <cfoutput>
    #i.id# #i.title# <br />
    </cfoutput>
  
</cfloop>

<!--- Loop to access array number --->
<cfloop array ="#arryRe#" item="item" index="i">

    <cfoutput>
    #i# <br />
    </cfoutput>
  
</cfloop>

Solution

  • Simplifying your code a bit, and adding local scope (assuming you're in a function), here's another way to do this, too:

    <cfset local.arrayRe = [
        {"id": "14", "title": "Title Fourteen"}
        , {"id": "15", "title": "Title Fifteen"}
    ] />
    
    
    <cfloop array="#local.arrayRe#" index="local.i" item="local.stItem">
        <cfoutput>
            Item ##: #local.i#, ID: #local.stItem.id#, Title: #local.stItem.title#<br />
        </cfoutput>
    </cfloop>