user747291
user747291

Reputation: 821

Create a list in a loop

I am trying to create a comma separated list inside a loop, but I think I am missing something. When I dump item_id_list, I just get items separated by a space - not a comma. Can anyone point what am I missing?

<cfloop array="data" index="doc">
    <cfif structKeyExists(doc, "id") >
        <cfset the_item_id = doc.id /> 
    </cfif>
  <cfset item_id_list = ''/>
  <cfset item_id_list = listappend(item_id_list,'#the_item_id#',',')/>
</cfloop>

Upvotes: 1

Views: 2609

Answers (2)

Evik James
Evik James

Reputation: 10473

Create the list outside of the loop:

<cfset item_id_list = "" />
<cfloop array="#data#" index="doc">
   <cfif structKeyExists(doc, "id") >
       <cfset item_id_list = listappend(item_id_list, doc.id, ",") />
   </cfif>
</cfloop>

Upvotes: 10

Shawn
Shawn

Reputation: 4786

Will this work?

<cfset item_id_list = ArrayToList(data.id)>

EDIT: Oops. Can't reference a struct in an array like that. Instead try:

<cfscript>
    item_id_list = "" ;
    for (row in data) {
        if (structkeyexists(row,"id") ) {
            item_id_list = listappend(item_id_list,row.id) ;
        }
    }
</cfscript>

For loops like this, cfscript syntax is easier to see.

Upvotes: 0

Related Questions