First of all, You need to download the “Asp Associative Array class” then include the file “AssociativeArrayClass.asp” in your asp page.
Right now, You can start declaring associative arrays in ASP with the following syntax:
Dim Person Set Person = New AssociativeArray Person("name") = "Max" Person("surname") = "Vergelli" Response.Write Person("name") & " " & Person("surname")
In the above example, the key “name” in “Person” object, stores “Max” value. You can set strings or integers for the key and any object/variant type for the relative value. However, You can not set key with Null or “” strings like the following:
'invalid keys... Person(Null) = "Null Key" Person("") = "Empty String" Dim undefined Person(undefined) = "Variable Not Initialized" Response.Write Person("") & Person(Null) & Person(undefined)
How to get every item of the associative array:
You can make a “For Each” loop on the array like in the following code
For Each element In Person.Items Response.Write element.Key & " : " & element.Value & vbCrLf Next
“Person.Items” gets all the items inside the associative array and for each item You can get “Key” and “Value” properties.
How to copy an associative array:
Dim Person_Clone 'it's a Variant type Set Person_Clone = Person 'NOTE: Use "Set" statement! 'print values Response.Write Person_Clone("name") & " " & Person_Clone("surname") & vbCrLf 'get each key/value For Each element In Person_Clone.Items Response.Write element.Key & " : " & element.Value & vbCrLf Next
How to create nested associative arrays…
You can create infinite nested associative arrays and accessing them like the following:
Dim Person Set Person = New AssociativeArray Person("name") = "Max" Person("surname") = "Vergelli" Dim People Set People = New AssociativeArray People(1) = Person People(2) = Person People(3) = Person Response.Write People(1)("name") & " " & People(1)("surname")
Besides, You can enumerate all the keys/values inside the “People” associative array object
For Each element In People.Items Dim el_person Set el_person = element.Value Response.Write el_person("name") & " : " & el_person("surname") & vbCrLf Next
Leave a Reply