Solved

Ubound in Multi-dimensional array

Posted on 2008-06-12
7
8,962 Views
Last Modified: 2012-06-21
I'm creating a dynamic favourites list using arrays.

So far all I wanted to do was to make sure I can create the array, add and item, check the size with ubound and remove an item,  writing this to the page as I go to make sure it works.

It all works fine in a normal array but once I've created a multi dimensional array the ubound no longer works and anything I do based on the ubound value fails after that.

Bear in mind that I wrote the syntax by making it up as I went along using code bits I've found and articles I read and what knowledge I have of VB Script. So it's not necessarily optimal. That being disclaimed here is the code:

<% Dim myArray() 'Create the dyamic array
 ReDim myArray(1,4) 'give it a size with redim

 'fill the array with items
myArray(0,0) = "Skye"
myArray(1,0) = "12 months"
myArray(0,1) = "Sto"
myArray(1,1) = "40 years"
myArray(0,2) = "Ilana"
myArray(1,2) = "38 years"
myArray(0,3) = "Jamie"
myArray(1,3) = "13 years"
myArray(0,4) = "Ribi"
myArray(1,4) = "3 years"
%>

<strong>The first array, written to the page</strong><br>

<% 'write the array items to the page
  For i = 0 to 4
 response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i)& "<br>")
 Next   %>
 
 <br> <% 'find the size of the array and write that to the page %>
 <strong>The size of the first array is <%  = UBound(myArray)   -UBound(myArray)   - LBound(myArray) %></strong><br><br>
 

<% Dim maxNum, newMaxNum 'create a current size variable and set it equal the array size and create a new max size variable
maxNum =  UBound(myArray) - LBound(myArray)
newMaxNum = MaxNum + 1 'grow it by one place using the current size + 1%>
<% ReDim Preserve myArray(1,newMaxNum)  'redim and preserve the array %>
 
<% myArray(0,newMaxNum) = "Heanly"
myArray(1,newMaxNum) = "3 years"'Give the new item a name%>
 
<% 'write the new array to the page
  For i = 0 to newMaxNum
 response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i) & "<br>")
 Next   %>
 
 <br><strong>The size of the new array is <%  = UBound(myArray) - LBound(myArray)  %> </strong><br><br>


<strong> Remove an item from the Array</strong><br>

<%  
      
removedItem = False
    Dim itemToRemove
    itemToRemove = "Sto"
    arrayLength = UBound(myArray)

    for i = 0 to arrayLength
        if (myArray(1,i) = itemToRemove) then
            ' If we found our search term in array
            ' we are copying array to a new array list
            myArray(i) = myArray(arrayLength)
            ' So now our first value must be TRUE
            removedItem = True
        end if
    next

    if (removedItem = True) then
        ' Let's make a new array and pass all values
        redim preserve myArray(arrayLength - 1)
    end if    %>
      
      <% newMaxNo = UBound(myArray) - LBound(myArray)  %>
      
      <% 'write the array sans removed item to page %>
      <br>
        <% For i = 0 to newMaxNo %>
 <% response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i)) %><br>
 <% Next %>
 
 <br><br>
 <strong>Add yet another item to the array</strong><br><br>
 
 <%maxNum =  UBound(myArray) - LBound(myArray)
newMaxNum = MaxNum + 1 'grow it by one place using the current size + 1%>
<% ReDim Preserve myArray(1,newMaxNum)  'redim and preserve the array %>
 
<% myArray(0,newMaxNum) = "Moss"
myArray(1,newMaxNum) = "10 years"'Give the new item a name%>
 
<% 'write the new array to the page
  For i = 0 to newMaxNum
 response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i) & "<br>")
 Next   %>

0
Comment
Question by:Gerano
  • 3
  • 2
  • 2
7 Comments
 
LVL 38

Expert Comment

by:Shift-3
Comment Utility
I'm not sure if I see exactly what you're trying to accomplish, but UBound checks the upper limit of the first dimension of an array by default.  To check the second dimension, use UBound(myArray, 2).
http://www.w3schools.com/vbscript/func_ubound.asp
0
 
LVL 9

Expert Comment

by:gregcmcse
Comment Utility
The MUCH easier way to do this is with a Dictionary object if you only need 2 elements in one direction.

Set dMyDict = CreateObject("Scripting.Dictionary")
dMyDict .CompareMode = 1   ' Text compare -- case insensitive
 ' Add elements -- note you don't need to redim
dMyDict ("Skye") = "12 months"
dMyDict ("Sto") = "40 years"
dMyDict ("Ilana") = "38 years"
dMyDict ("Jamie") = "13 years"
dMyDict ("Ribi") = "3 years"
dMyDict("DeleteMe") = "0 years"

' Change an element
dMyDict ("Skye") = "1 year"

' Find out if an element exists -- if it does, then delete the element
if dMyDict.Exists("DeleteMe") Then dMyDict.Delete("DeleteMe")

' Iterate through your Dictionary object
For each strName in dMyDict.Keys
   response.write(strName & "&nbsp;" & dMyDict(strName) & "<br>")
Next

Note:  I've read that unpredictable things happen when you delete an object out of a dictionary object you are iterating through -- so don't do that.

If you need more than 2 elements, consider using two dictionary objects or a RecordSet object.  That's really beyond the scope of this question, though at this point.
0
 

Author Comment

by:Gerano
Comment Utility
I will look at the dictionary object as a seperate issue and try to get my mind around it. Thanks grecmcse.
In the interim I would like to master the array business.
Shift-3 you were right, that bit of syntax was what I was missing.
However, there is still one problem. In the new code I posted below, the wrong item is removed from the array. Stoan is specified but Heanly is removed. I was thinking that I'm not referencing the correct "column" to be deleted.
On line 57 I then change myArray(1,i) to myArray(0,i) but then get a subscript out of range error on line 60. Likewise if I make the same change to line 60, the subscript out of range error occurs.
What am I missing?
Gerano



<% Dim myArray() 'Create the dyamic array
 ReDim myArray(1,4) 'give it a size with redim

 'fill the array with items
myArray(0,0) = "Skye"
myArray(1,0) = "12 months"
myArray(0,1) = "Stoan"
myArray(1,1) = "40 years"
myArray(0,2) = "Ilana"
myArray(1,2) = "38 years"
myArray(0,3) = "Jamie"
myArray(1,3) = "13 years"
myArray(0,4) = "Ribi"
myArray(1,4) = "3 years"
%>

<strong>The first array, written to the page</strong><br>

<% 'write the array items to the page
  For i = 0 to 4
 response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i)& "<br>")
 Next   %>
 
 <br> <% 'find the size of the array and write that to the page %>
 <strong>The size of the first array is <%  = UBound(myArray, 2)   - LBound(myArray) + 1%></strong><br><br>
 

<% Dim maxNum, newMaxNum 'create a current size variable and set it equal the array size and create a new max size variable
maxNum =  UBound(myArray, 2) - LBound(myArray)
newMaxNum = MaxNum + 1 'grow it by one place using the current size + 1%>
<% ReDim Preserve myArray(1,newMaxNum)  'redim and preserve the array %>
 
<% myArray(0,newMaxNum) = "Heanly"
myArray(1,newMaxNum) = "3 years"'Give the new item a name%>
 
<% 'write the new array to the page

  For i = 0 to newMaxNum
 response.write (myArray(0,i))&"&nbsp;"&(myArray(1,i) & "<br>")
 Next   %>
 
 <br><strong>The size of the new array is <%  = UBound(myArray, 2) - LBound(myArray,2)  + 1%> </strong><br><br>


<strong> Remove an item from the Array</strong><br>

<%  
      
removedItem = False
    Dim itemToRemove
    itemToRemove = "Stoan"
    arrayLength = UBound(myArray,2)

    for i = 0 to arrayLength
        if (myArray(1,i) = itemToRemove) then
            ' If we found our search term in array
            ' we are copying array to a new array list
            myArray(1,i) = myArray(arrayLength)
            ' So now our first value must be TRUE
            removedItem = True
        end if
    next

    if (removedItem = True) then
        ' Let's make a new array and pass all values
        redim preserve myArray(arrayLength - 1)
    end if    %>
      
      <% 'write the array sans removed item to page %>
      <br>
        <% For i = 0 to 4%>
 <% response.write (myArray(0,i)) &"&nbsp;"& (myArray(1,i) ) %><% If i = "" Then %><% Else %><br><% End If %>
 <% Next %>
 
 <br><br>
 <strong>Add yet another item to the array</strong><br><br>
 
 <%maxNum =  UBound(myArray, 2) - LBound(myArray,2) 'get the latest array Size
newMaxNum = MaxNum + 1 'grow it by one place using the current size + 1%>
The Array size is now: <% =NewMaxNum %><br><br>
<% ReDim Preserve myArray(1,newMaxNum)  'redim and preserve the array %>
 
<% myArray(0,newMaxNum) = "Moss"
myArray(1,newMaxNum) = "10 years"'Give the new item a name%>
 
<% 'write the new array to the page
  For i = 0 to newMaxNum
 response.write(myArray(0,i))&"&nbsp;"&(myArray(1,i) & "<br>")
 Next   %>
 
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:Gerano
Comment Utility
I have now turned to the Dictionary Object to make my favorites list go. It is going well so far. I'm adding and removing items without problems and able to write it to an HTML table.
I want to use it as a shpooing cart type element that a user can save a Database and retrieve later to edit.
I have a few issues that I have to solve, these are presented in my questions below:
How do I write the dictionary object to a database as a single record? As a string, a variable or something else?
How do I write it back to the page and then add an item? I.e. do I recreate the Dict Obj first and then populate from the DB, and how?
Let me know if I should up points on offer for this.
Thanks
Gerano
0
 
LVL 38

Expert Comment

by:Shift-3
Comment Utility
You can get all of the dictionary keys or items into a single string by first making them into an array.
arrKeys = objDictionary.Keys
arrItems = objDictionary.Items
http://www.devguru.com/Technologies/vbscript/QuickRef/dictionary.html

Then put them together with the Join fuction.
strKeys = Join(arrKeys)
strItems = Join(arrItems)
http://www.w3schools.com/vbscript/func_join.asp

As for writing them into your database and retrieving them, I'm unsure as to the best method.
0
 
LVL 9

Accepted Solution

by:
gregcmcse earned 250 total points
Comment Utility
To pass them to another page, I'd put them together like this:

strKeys = Join(objDictionary.Keys,",")
strValues = Join(objDictionary.Values,",")

Then post them to the new page or put them in a cookie or whatever passing method you prefer.

Then on the new page, bring them back into the strKeys and strValues strings and then:

Set dMyDict = Server.CreateObject("Scripting.Dictionary")
dMyDict.CompareMode = 1

arrKeys = Split(strKeys,",")
arrValues = Split(strValues,",")

for i = 0 to uBound(arrKeys)
    dMyDict(arrKeys(i)) = arrValues(i)
next ' i


To put them in a database, it depends on whether or not you want to open a RecordSet object.

EITHER:

For Each strKey in dMyDict.Keys
    oRS.Add strKey, dMyDict(strKey)
Next ' strKey

OR:
For Each strKey in dMyDict.Keys
    strSQLCMD = "INSERT INTO mytablename values('" & strKey & "','" & dMyDict(strKey) & "')"
Next ' strKey

If you have want multiple fields in your dictionary object value.  For example:
Name, Age, FavColor
dMyDict("Brian") = "11,blue"

You could get that into the DB by replacing "dMyDict(strKey)" in the strSQLCMD variable with "Replace(dMyDict(strKey),",","','")".

Then the [11,blue] becomes [11','blue].  Note that in the code line, you have single quotes surrounding each text value.  If age was actually a number field, this gets more complicated as the correct SQL would be "INSERT INTO mytablename values('Brian',11,'blue')".

Also worth noting -- this assumes your database schema has 3 fields in that order (Name, Age, FavColor).  If they're in a different order, your insert command needs to specify the order you're inserting them in:
"INSERT INTO mytablename (Name, FavColor, Age) values ('Brian','blue',11)"

If you need more help on accessing SQL databases from ASP, you should probably open a new question as we're getting way beyond the scope of your original question here.
0
 

Author Closing Comment

by:Gerano
Comment Utility
Thanks a stack. Your assistance was really helpful. It took me another week of playing with this to make it do what I wanted it to, kind of elaborate but it's working brilliantly. Thanks again.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

It is a general practice to get rid of old user profiles on a computer  in a LAN environment. As I have been working with a company in a LAN environment where users move from one place to some other place at times. This will make many user profil…
Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now