Reputation: 21
I'm fairly new, as you'll see. I want to create the following variables:
V1
= word 1 in my queryV2
= word 2 in my queryI can do this statically like so:
<cfset V1=#qryGetWords["WordName"][1]#>
<cfset V2=#qryGetWords["WordName"][2]#>
<cfset V3=#qryGetWords["WordName"][3]#>
<cfset V4=#qryGetWords["WordName"][4]#>
but I want to do it dynamically. I've seen other answers but I can't get them to work either. Can anything like the following work with a tweak to the syntax?
<cfloop query="qryGetWords" index="i">
<cfset "V#i#" = #qryGetWords["WordName"]["i"]#>
</cfloop>
Can I not have an index and a query within the cfloop?
Upvotes: 2
Views: 124
Reputation: 28873
Since you are using a query loop, you already have access to a built in index ie query.currentRow
. As with the cfoutput tag:
When you specify a query attribute, this tag loops over the query rows .... It also sets the query.currentRow variable to the current row being processed.
Example:
<cfloop query="qryGetWords">
<!--- within the loop, you could also use the shortcut: qryGetWords.WordName --->
<cfset variables["V"& currentRow] = qryGetWords["WordName"][currentRow]>
</cfloop>
Update:
While that answers the question asked, Dan's answer raises a good point. It may not be the best way to store information. If you elaborate on your overall goal, we can suggest an approach that might be more flexible.
Upvotes: 5
Reputation: 4694
if you need to loop over them or reference by index later then an array is an option to consider
if so then you can build up array like this
<cfset words = [] />
<cfloop query="queryname">
<cfset arrayappend(words, queryname.wordname) />
</cfloop>
or through internal functions by way of lists
<cfset words = listtoarray(valuelist(queryname.wordname)) />
and if content may contain commas then must use another delimiter of your choice (new line chr(10) may be safest though I use pipes "|" often, cf loves character delimited strings)
<cfset words = listtoarray(valuelist(queryname.wordname, chr(10)), chr(10)) />
then you can reference statically like so
<cfif something eq words[3]>
#blah#
</cfif>
or dynamically like so (or probably easier on newer versions, I am still on CF8)
<cfloop from="1" to="#arraylen(words)#" index="i">
<cfoutput><div>#i#: #words[i]#</div>
</cfloop>
this also allows you to dump all words at once and operations on arrays that would not be possible with dynamically generated variable names/structkeys
Upvotes: 1
Reputation: 32905
<cfloop query="qryGetWords">
<cfset "V#qryGetWords.currentRow#" = qryGetWords.WordName>
</cfloop>
note: use of qryGetWords.
inside the cfloop query=
is optional. You can omit it and it'll still work. Some prefer to use it, some don't. That's your choice.
or
<cfloop from="1" to="#qryGetWords.recordCount#" index="i">
<cfset "V#i#" = qryGetWords.WordName[i]>
</cfloop>
Upvotes: 2