Reputation: 6110
I have query with multiple line of records. I would like to output each line in structure with column name key. After looping over the query records I want to set that structure in array. So far I have correct format of my data but for some reason each line of data is the same. Seems that all the data is coming from one row. Here is example of my code:
<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>
If I try to dump array this is how my output looks like:
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]
Here is example of actual data query:
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
As you can see data in array of structures repeats the data from the last row. I'm not sure where is the bug in my code. If anyone knows how to fix this problem please let me know. Thanks.
Upvotes: 0
Views: 377
Reputation: 6550
The problem is the code only creates a single structure. So all those loops are doing is updating that one structure, and appending the same structure to the array, over and over again.
To populate the array with separate structures, you must create a new structure before the inner the loop:
<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>
Upvotes: 3