How to get a dynamic attribute name in cfloop over query in ColdFusion

十年热恋 提交于 2019-12-01 16:19:07

问题


I'm inside a cfloop over a query. I want to get an attribute, but I won't know what that attribute will be until runtime. Using #qryResult[MyAttr]# fails with the error "Complex object types cannot be converted to simple values." What is the syntax for doing this?

Here is a simplified example:

<cfquery datasource="TestSource" name="qryResult">
    SELECT * FROM MyTable
</cfquery>

<cfloop query="qryResult">
    <cfset MyAttr="autoid" />
    <cfoutput>
        Test 1: #qryResult.autoid# <br/>  <!--- succeeds --->
        Test 2: #qryResult[MyAttr]# <br/> <!--- fails --->
    </cfoutput>
</cfloop>

回答1:


<cfloop query="qryResult">
  <cfset MyAttr="autoid" />
  <cfoutput>
   Test 1: #qryResult.autoid# <br/>  <!--- succeeds --->
   Test 2: #qryResult[MyAttr][qryResult.CurrentRow]# <br/> <!--- succeeds --->
  </cfoutput>
</cfloop>

CurrentRow is implicit in the literal syntax (query.col). It is tied to the index of <cfloop query="...">/<cfoutput query="..."> (or 1 when used outside a loop).

Mentioning it explicitly is necessary in the "array index" syntax (query[col][row]), because query[col] alone returns the column object (which is the "complex type" the error refers to).

Side effect: You can use this for random access to a query result outside of a loop (i.e. as a multi-dimensional array). Once you know the numbers of the rows that interest you, you can access the rows directly.



来源:https://stackoverflow.com/questions/2581394/how-to-get-a-dynamic-attribute-name-in-cfloop-over-query-in-coldfusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!