ColdFusion - Create multidimensional array dynamically

1.5k views Asked by At

I'm using CF 10. As a script is running, I am creating an array containing distinct values that represent a single vehicle. I'm initializing the array at the top of my script using

<cfset myArray = ArrayNew(1)>

Then as I am running my script I'm appending to it using...

<cfset temp = ArrayAppend(myArray, myQuery.VIN)>

This all works fine, but what I want to do is after each section in the script is reached, I want to update any VINS in my current section query so that they are an array of values. So the Array that was..

[1]["VIN NUMBER 123"] [2]["VIN NUMBER 456"]

becomes...

[1]["VIN NUMBER 123"]["VALUE1"] ["VALUE2"] ["VALUE3"] [2]["VIN NUMBER 456"]["VALUE2"]

I thought I could do something like this...

<cfset vindex = ArrayFind(myArray,vinToFind)>
<cfif NOT IsArray('myArray[vindex]')>
     <cfset myArray[vindex] = ArrayNew(1)>
</cfif>
<cfset temp = ArrayAppend(myArray[vindex],valueToAppend)>

but in the end, my array is still one dimensional. What am I doing wrong?

1

There are 1 answers

1
Alex On BEST ANSWER

I recommend an array of arrays as suggested by @ale.

<cfset myArray = ArrayNew(1)>

<!--- check if the VIN is already present --->
<cfset vindex = ArrayFind(myArray, vinToFind)>

<!--- the VIN was found --->
<cfif (vindex gt 0)>

    <!--- if the VIN is still on its own, transform it to an array --->
    <cfif NOT IsArray(myArray[vindex])>
        <cfset temp = myArray[vindex]> <!--- remember current VIN --->
        <cfset myArray[vindex] = ArrayNew(1)> <!--- transform present index to an array --->
        <cfset ArrayAppend(myArray[vindex], temp)> <!--- add VIN back in --->
    </cfif>

    <!--- add the VIN --->
    <cfset ArrayAppend(myArray[vindex], valueToAppend)>

<!--- VIN is not present yet --->
<cfelse>
    <cfset ArrayAppend(myArray, valueToAppend)>
</cfif>

Here are some tips:

  1. ArrayAppend(1) can be written as [].
  2. ArrayAppend(myArray, value) can be written as myArray.add(value).
  3. There's usually no need to store the return of ArrayAppend as it will always return true. Just go with <cfset ArrayAppend(myArray, value)>.
  4. IsArray expects a variable, not a string. IsArray("myArray") will always return false while IsArray(myArray) would return true.

The above code using array literals and the add method.

<cfset myArray = []>

<!--- check if the VIN is already present --->
<cfset vindex = arrayFind(myArray, vinToFind)>

<!--- the VIN was found --->
<cfif (vindex gt 0)>

    <!--- if the VIN is still on its own, transform it to an array --->
    <cfif not isArray(myArray[vindex])>
        <cfset myArray[vindex] = [ myArray[vindex] ]> <!--- transform present index to an array --->
    </cfif>

    <!--- add the VIN --->
    <cfset myArray[vindex].add(valueToAppend)>

<!--- VIN is not present yet --->
<cfelse>
    <cfset myArray.add(valueToAppend)>
</cfif>