Solved

Ubound in Multi-dimensional array

Posted on 2008-06-12
7
8,976 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
ID: 21772278
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
ID: 21773255
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
ID: 21776590
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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

Author Comment

by:Gerano
ID: 21792802
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
ID: 21794554
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
ID: 21796305
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
ID: 31466645
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

911 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

23 Experts available now in Live!

Get 1:1 Help Now