Coldfusion and Associative Arrays

I am used to handling my associative arrays PHP style, where I would have something like the following

array[day][time] = count

This allows me to easily count the number of times something appears and its an easy structure to work with. In my case here, I am reading a resultset from a database and getting something like this to work would be really helpful

How would I do the same type of thing in Coldfusion?

Upvotes: 3

Views: 5554

Answers (3)

Russ
Russ

Reputation: 1951

You can do this with Coldfusion arrays, too.

array = [[], []];// initialize array

array[1][1] = 1;// set a value in the array

Just remember that Coldfusion arrays start at an index of 1, not 0.

Upvotes: 0

BKK
BKK

Reputation: 2073

This is a followup to a comment Reginold had about checking whether the struct is defined:

<cfset thisvar = '04/MAR/2012'>
<cfset thatvar = '04:11'>
<cfset myStruct[thisvar][thatvar] = 'test'>

<!--- Check first key, then second --->
<cfif structKeyExists(myStruct,thisvar) and structKeyExists(mystruct[thisvar],thatvar)>
    Both Keys Exist.<hr>
</cfif>

<!--- Alternative Check --->
<cfif isDefined('myStruct.#thisvar#.#thatvar#') >
    Key Exists.<hr>
</cfif>

<cfdump var="#myStruct#"> 

Upvotes: 4

Mark A Kruger
Mark A Kruger

Reputation: 7193

This looks like a structure to me - and you can create it easily the way you are used to:

<cfscript>

   myStruct = { day= { time = count}};

</cfscript>

Or using the old syntax which perhaps outlines it better.

<cfset mySTruct = structNew()/>
<Cfset mySTruct.day = structNew()/>
<Cfset myStruct.day.time = count/>

Remember too that a ColdFusion query object is already an exceedingly useful little data construct with a format of queryName[struct][row] - and query of a query (where you can utilize SQL to simply query a query object) allows easy access to this data as well.

Hope this helps you Reg. Good luck.

Upvotes: 11

Related Questions