1

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>

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Now I've seen a new way of doing things.
Remember to encode your output with encodeForHtml. That innocent title might cause you problems in the future.
0

Just figured it out.

<cfloop array ="#arryRe#" item="item" index="i">

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.