Skip to main content
Inspiring
July 17, 2010
Question

2D Array question

  • July 17, 2010
  • 2 replies
  • 686 views

Hi,

I have two arrays, call them arrOne and arrTwo

How can I put arrTwo inside of the first position in arrOne


So say I have values like this in arrOne:

<cfset arrOne = ArrayNew(1)>
<cfset arrOne[1] = "John">
<cfset arrOne[2] = "Paul">

<cfset arrTwo = ArrayNew(1)>
<cfset arrTwo[1] = "Fruit">
<cfset arrTwo[2] = "Meat">


I want to put arrTwo inside of arrOne in the first position.  I tried using ArrayInsertAt, but it overwrote the
first position which is not what I want.  The insert shouldn't overwite John's name. It should appear nested under it

I'm trying to somehow get arrTwo into arrOne[1][1]... something like that...

Any help appreciated...

-ws

This topic has been closed for replies.

2 replies

Inspiring
July 17, 2010

CF doesn't really have the concept of multi-dimensional arrays like other languages might, it just effects the same result by allowing any given array element to be, itself, an array.

So there's no trick to doing what you want: just prepend your second array to the first one.

That said, a 2-D array is seldom the best data structure for most requirements. What is the nature of your data? Are you sure you'd not be better off with an array of structs, or possibly having a struct with an element that is an array?

--

Adam

Inspiring
July 20, 2010

I would agree with Adam regarding the structures.  However, if you need to go down the array route, you're looking for syntax like this:

<cfset arrTwo = ArrayNew(1)>
<cfset arrTwo[1] = "Fruit">
<cfset arrTwo[2] = "Meat">

<cfset arrOne = ArrayNew(2)>
<cfset arrOne[1][1] = "John">

<cfset arrOne[1][2] = arrTwo>

Inspiring
July 17, 2010

Initialize your array as 2D.