Skip to main content
July 25, 2014
Answered

Not getting all results in Array Populated from Query

  • July 25, 2014
  • 3 replies
  • 532 views

When running this it is only giving me the last value of my query in the array. Any thoughts on why this is happening? I appreciate any assistance. Thank you

<cfset result = arrayNew(1) />

           <cfset ArrayMedSchools = structNew() />

         

        <cfloop query="GetMedSchool" >

             <cfoutput>

              <cfset ArrayMedSchools.name = Institution />

              <cfset ArrayMedSchools.id = InstitutionID />

              <cfset arrayAppend(result,ArrayMedSChools) />

             </cfoutput>

        </cfloop>

        <cfset ArrayMedSchools = structNew()/>

       

        <cfdump var="#GetMedSchool#" label="Original Query">

        <cfdump var="#result#" label="resulting array">

    This topic has been closed for replies.
    Correct answer

    I figured it out.

    I had the   <cfset ArrayMedSchools = structNew()/> outside the loop instead of inside the loop.

    3 replies

    Correct answer
    July 25, 2014

    I figured it out.

    I had the   <cfset ArrayMedSchools = structNew()/> outside the loop instead of inside the loop.

    July 25, 2014

    Thanks everyone for the responses. This was nagging me for the past 2 days.

    Dave Ferguson
    Participating Frequently
    July 25, 2014

    Here you go... this is how you would want to do it.

    <cfset result = [] />

    <cfloop query="GetMedSchool" >

    <cfset result[ArrayLen(result)+1] = {name = GetMedSchool.Institution, id = GetMedSchool.InstitutionID}>

    </cfloop>

    <cfdump var="#GetMedSchool#" label="Original Query">

    <cfdump var="#result#" label="resulting array">

    HTH,

    --Dave

    Participating Frequently
    July 25, 2014

    So your query has X rows.  Does your array have the values for the last row in your query, duplicated X times?  Or does it just have one element, with the values from the last row in the query?

    One thing you might want to try is resetting the structure within your query loop:

    <cfset result = arrayNew(1)>

    <cfset ArrayMedSchools = structNew()>

    <cfloop query="GetMedSchool">

        <cfset ArrayMedSchools = structNew()>

        <cfset ArrayMedSchools.name = GetMedSchool.Institution>

        <cfset ArrayMedSchools.id = GetMedSchool.InstitutionID>

        <cfset arrayAppend(result, ArrayMedSchools)>

    </cfloop>

    <cfdump var="#GetMedSchool#" label="Original Query">

    <cfdump var="#result#" label="resulting array">

    Also note that you don't need to use <cfoutput> within your loop there.