0

我有多行记录的查询。我想用列名键输出结构中的每一行。在遍历查询记录后,我想在数组中设置该结构。到目前为止,我的数据格式正确,但由于某种原因,每一行数据都是相同的。似乎所有数据都来自一行。这是我的代码示例:

<cfset strGraphData = StructNew()>
<cfset arrGraphData = arrayNew(1)>

<cfquery name="getGraphData" datasource="myDB">
    SELECT gr_date, gr_LabelA,  gr_LabelB
    FROM GraphData WITH (NOLOCK)
    WHERE gr_ID = <cfqueryparam value="#arguments.graphID#" cfsqltype="cf_sql_integer">
    ORDER BY gr_date ASC
</cfquery>

<cfoutput query="getGraphData">
    <cfloop list="#getGraphData.getColumnNames()#" index="columnName">
        <cfset strGraphData[columnName] = Trim(getGraphData[columnName][getGraphData.CurrentRow])>
    </cfloop>
    <cfset arrayAppend(arrGraphData, strGraphData)>
</cfoutput>

如果我尝试转储数组,这就是我的输出的样子:

array
1   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

2   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

3   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

4   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

5   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

6   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

7   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

8   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

9   
struct
GR_DATE 2014-05-12 00:00:00.0
GR_LABELA   17
GR_LABELB   [empty string]

以下是实际数据查询的示例:

GR_DATE
2014-01-14 00:00:00.000
2014-02-04 00:00:00.000
2014-02-18 00:00:00.000
2014-03-04 00:00:00.000
2014-03-18 00:00:00.000
2014-04-01 00:00:00.000
2014-04-15 00:00:00.000
2014-04-29 00:00:00.000
2014-05-12 00:00:00.000

GR_LABELA
1
3
5
5
10
16
16
16
17

GR_LABELB
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL
    NULL

如您所见,结构数组中的数据重复了最后一行的数据。我不确定我的代码中的错误在哪里。如果有人知道如何解决此问题,请告诉我。谢谢。

4

1 回答 1

3

问题是代码只创建了一个结构。所以所有这些循环所做的就是更新一个结构,并一遍又一遍地将相同的结构附加到数组中。

要使用单独的结构填充数组,您必须在内部循环之前创建一个新结构:

<cfoutput query="getGraphData">
    <!--- create new structure here --->
    <cfset strGraphData = StructNew()>

    <cfloop list="#getGraphData.getColumnNames()#" index="columnName">
        <cfset strGraphData[columnName] = Trim(getGraphData[columnName][getGraphData.CurrentRow])>
    </cfloop>

    <cfset arrayAppend(arrGraphData, strGraphData)>
</cfoutput>
于 2018-02-07T15:17:49.977 回答