16

Giving the Array of Structure below:

enter image description here

I am able to print out all values from all fields by doing:

    <cfset ColumnNames  = structKeyArray(ApiData[1])>                       
    <cfset ColumnLength = ArrayLen(ColumnNames)>    

    <cfloop from="1" to="#ArrayLen(ApiData)#" index="i">            
       <cfdump var="#ApiData[i].Created#">              
       <cfdump var="#ApiData[i].Name#">
               ...and so on

Now I am trying to loop through all fields so that I dont have to actually write the name of each field. How do I do this dynamically? Something like:

    <cfloop from="1" to="#ArrayLen(ApiData)#" index="i">    
      <cfloop from="1" to="#ColumnLength#" index="i">
              <!---<cfdump var="#ApiData[i]." + "#ColumnNames[i]#" + "#">--->
              <!---<cfdump var="#ApiData[i].ColumnNames[i]#">--->
      </cfloop>
    </cfloop>

I am not a ColdFusion guy, just helping a buddy and the ColdFusion syntax is very different from .Net :-)

Thank you for your help

1
  • 3
    My vote on this question should get your reputation into 3 digits. You owe me a beer. Commented Nov 1, 2013 at 11:45

1 Answer 1

24
<cfloop from="1" to="#arrayLen(ApiData)#" index="i">
  <cfset data = ApiData[i]>
  <cfloop collection="#data#" item="key">
    #key#:#data[key]#
  </cfloop> 
</cfloop>

Or you can use CFScript, which should be much easier to pick up.

for (d in ApiData)  // for-in loop for array
{
  for (key in d)  // for-in loop for struct
  {
     writeOutput(key & ":" & d[key]);
  }
}

use this link: http://www.learncfinaweek.com/week1/Looping/

Sign up to request clarification or add additional context in comments.

4 Comments

@Max - Since you did not mention the CF version, be aware that for-in-loops with arrays requires CF9.0.1+.
That did not work. It seems that your solution applies to a single structure. Remember, I have to loop through an Array of Structures. I tried accessing the first structure of the Array by doing the following: <cfloop collection="#ApiData[1]#" item="key"> #key#:#ApiData[key]# </cfloop> I am using CF 8 by the way -- thanks
I changed to: <cfdump var="#ApiData[1][key]#"> and it actually worked. Now all I need is to make it dynamic - thank you!
@Max hmm, sorry didn't know you're still in CF8. I've updated the CFML answer and it should work for you.

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.