Two Dimensional Arrays
A 2 dimensional array is a tough concept for a lot of people to grasp. But once it clicks, it’s usually pretty easy from then on. The best way to think of a 2 dimensional array is as a table in your database. The first dimension would be the name of your fields across the top. The second dimension would be your rows of information.
Let’s create a 2 dimensional array.
What we’ve done here is create an array that in the first dimension has 2 constants which we will define in a minute. The second dimension defines how many rows of information this array can hold, in this case 100. Now we define the constants that will be contained in our first dimension.
CONST example_field_1 = 0
CONST example_field_2 = 1
Now take a look at the constants we’ve just defined and compare them with the array defined earlier and the graphic shown above. When you understand how this works, move on to the next part.
Now we need to assign values (or input rows) into our array. Think of it as simply filling in info in our fields in our database table. First we need to fill in our example_field_1 field.
cart(0,0) = “some text”
Now we fill in our 2nd field in our table…keep in mind we’re just using the words table and fields to keep the picture straight. An array does not actually contain a table and a field…it’s just a concept we’re using here.
cart(1,0) = “some more text”
Now we will fill in 2 more rows in our array.
cart(0,1) = “test”
cart(1,1) = “test 2”
cart(0,2) = “more stuff”
cart(1,2) = “even more stuff”
Compare the above array with the table graphic above and you should start to see how the two are very much alike and start to understand 2 dimensional arrays. Now we want to loop through the contents of our array and display them. Here’s how we do it. We’re going to use a for loop.
For i = 0 to ubound(cart)
<%=cart(example_field_1,i)%> : <%=cart(example_field_2,i)%>
What we’ve done is set up a for loop, assign the value of 0 to i for the starting point in our loop, and then assign the upper bound of our array as the ending point of our loop. Then we loop through our array by printing out the contents of our values. Let us know if you run into problems or any questions by posting them on our messageboard. I know this kind of an array can be difficult to get, but just imagine 3 and 4 dimensional arrays…arghhh. We’ll deal with those sometime later when I have had more sleep:) Good luck! See ya next time.
Times Viewed: 18