Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Key in ColdFusion Structure

What is the proper syntax for creating a key within a ColdFusion structure which is an array? Preferably in the cfscript tags.

To give a clearer idea of what I'm trying to do, here's what I thought it might be:

StructInsert(account[i], "child[numChildren]", z);

where "child" was supposed to be an array and numChildren was a counter in a loop.

Obviously this doesn't work. It just gives me an error saying that the key "child[numChildren]" already exists.

like image 484
Jimmy Avatar asked Jan 26 '26 11:01

Jimmy


1 Answers

You say the "account" structure called "child" which is an array. This doesn't make any sense. If "child" is an array, it cannot be a structure. If it's a structure, it cannot be an array. An array can contain structs, and structs can contain arrays.

A struct is a map or hash, in other words, it consists of name value pairs. An array is a set or list of values. You can loop over them, or access them via their numeric index.

Let's make account an struct, and child an array.

<cfset Account = structNew() />
<cfset Account.Child = ArrayNew(1) />

Account is a struct, so you can use struct functions on it (structKeyExists, structInsert).
Account.Child is an array, so you can use array functions on it (arrayAppend, etc.). Account.Child, being an array, can contain pretty much any value in an entry, including complex values. So let's make Account.Child an array of structs.

let's say z in your example is a structure that looks something like this:

<cfset z = structNew() />
<cfset z.id = 1 />
<cfset z.name = "James" />

You could add this to Account.Child like so:

<cfset ArrayAppend(account.child,z) />

Or, you could do it directly via the index like so:

<cfset account.child[numChildren] = z />

NOW. Lets say you want to keep Account a struct, but you want to have 1 key for each child in the struct, not use an array. You can do this by using a dynamic key, like this:

<cfset Account["child_#numChildren#"] = z />

FYI, structInsert is generally an unnecessary function.

like image 131
Mark Avatar answered Jan 28 '26 04:01

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!