Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a comma separated list of quoted values

I need to create a list of country names within quotes and a comma at the end - except the last country name, like this: (I'm using ColdFusion 10)

  "Tuvalu",
  "Uganda",
  "Ukraine",
  "United Arab Emirates",
  "United Kingdom",
  "Uruguay"

  <cfquery name="query_names" datasource="MyDB">
   select short_desc
   from tbl_country
   where NVL(short_desc,' ') <> ' '
   order by short_desc
  </cfquery>
  <cfset TotalRec = "#query_names.Recordcount#">

  <cfloop query="query_names">
     <cfif query_names.Recordcount GT 271>
       <cfoutput>
         "#Trim(short_desc)#" & ","
       </cfoutput>
     <cfelse>
       <cfoutput>
         "#Trim(short_desc)#"
       </cfoutput>
     </cfif>
  </cfloop>

This loop result in country names within quotes, but no comma. So my loop result in:

  "Tuvalu"
  "Uganda"
  "Ukraine"
  "United Arab Emirates"
  "United Kingdom"
  "Uruguay"
like image 466
user1557856 Avatar asked Dec 05 '25 06:12

user1557856


2 Answers

If you really need double quotes, it is probably simpler to append the quoted values to an array and convert it to a list at the end. The ArrayToList function automatically handles the commas for you:

<cfset names = []>
<cfloop query="query_names">
    <cfset arrayAppend(names, '"'& short_desc & '"')>
</cfloop>

<cfoutput>#arrayToList(names)#</cfoutput>

Result:

"Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay" 

Side note, if single quotes, i.e., ' are acceptable, it is even simpler. Skip the looping and just use QuotedValueList():

 <cfoutput>#quotedValueList(query_names.short_desc)#</cfoutput>

Result:

'Tuvalu','Uganda','Ukraine','United Arab Emirates','United Kingdom','Uruguay'
like image 178
Leigh Avatar answered Dec 08 '25 01:12

Leigh


I hope listQualify() does the same in pretty easier way. isn't it???

<cfset myQry = queryNew("country","varchar",[["Tuvalu"],["Uganda"],["Ukraine"],["United Arab Emirates"],["United Kingdom"],["Uruguay"]])>
<cfdump var="#listQualify(valueList(myQry.country),'"')#" />

Also we can use quotedValueList() as Leigh mentioned, if we need single quoted list.

like image 23
Pothys Ravichandran Avatar answered Dec 08 '25 02:12

Pothys Ravichandran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!