?
? ????? PHP ??? ???? ??? ?? ??
Dictionary 對象用于在名稱/值對中存儲信息。
Dictionary 對象用于在名稱/值對(等同于鍵和項目)中存儲信息。Dictionary 對象看似比數(shù)組更為簡單,然而,Dictionary 對象卻是更令人滿意的處理關(guān)聯(lián)數(shù)據(jù)的解決方案。
比較 Dictionaries 和數(shù)組:
下面的實例創(chuàng)建了一個 Dictionary 對象,并向?qū)ο筇砑恿艘恍╂I/項目對,然后取回了鍵 gr 的項目值:
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
輸出:
The value of key gr is: Green
Dictionary 對象的屬性和方法描述如下:
屬性 | 描述 |
---|---|
CompareMode | 設(shè)置或返回用于在 Dictionary 對象中比較鍵的比較模式。 |
Count | 返回 Dictionary 對象中鍵/項目對的數(shù)目。 |
Item | 設(shè)置或返回 Dictionary 對象中一個項目的值。 |
Key | 為 Dictionary 對象中已有的鍵值設(shè)置新的鍵值。 |
方法 | 描述 |
---|---|
Add | 向 Dictionary 對象添加新的鍵/項目對。 |
Exists | 返回一個布爾值,這個值指示指定的鍵是否存在于 Dictionary 對象中。 |
Items | 返回 Dictionary 對象中所有項目的一個數(shù)組。 |
Keys | 返回 Dictionary 對象中所有鍵的一個數(shù)組。 |
Remove | 從 Dictionary 對象中刪除指定的鍵/項目對。 |
RemoveAll | 刪除 Dictionary 對象中所有的鍵/項目對。 |
指定的鍵存在嗎?
本例演示如何創(chuàng)建一個 Dictionary 對象,然后使用 Exists 方法來檢查指定的鍵是否存在。
<!DOCTYPE?html> <html> <body> <% dim?d set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" if?d.Exists("n")=?true?then ????Response.Write("Key?exists.") else ????Response.Write("Key?does?not?exist.") end?if set?d=nothing %> </body> </html>
返回一個所有項目的數(shù)組
本例演示如何使用 Items 方法來返回一個所有項目的數(shù)組。
<!DOCTYPE?html> <html> <body> <% dim?d,a,i,s set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" Response.Write("<p>The?values?of?the?items?are:</p>") a=d.Items for?i?=?0?To?d.Count?-1 ????s?=?s?&?a(i)?&?"<br>" next Response.Write(s) set?d=nothing %> </body> </html>
返回一個所有鍵的數(shù)組
本例演示如何使用 Keys 方法來返回一個所有鍵的數(shù)組。
<!DOCTYPE?html> <html> <body> <% dim?d,a,i,s set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" Response.Write("<p>The?value?of?the?keys?are:</p>") a=d.Keys for?i?=?0?To?d.Count?-1 ????s?=?s?&?a(i)?&?"<br>" next Response.Write(s) set?d=nothing %> </body> </html>
返回一個項目的值
本例演示如何使用 Item 屬性來返回一個項目的值。
<!DOCTYPE?html> <html> <body> <% dim?d set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" Response.Write("The?value?of?the?item?n?is:?"?&?d.item("n")) set?d=nothing %> </body> </html>
設(shè)置一個鍵
本例演示如何使用 Key 屬性來在 Dictionary 對象中設(shè)置一個鍵。
<!DOCTYPE?html> <html> <body> <% dim?d set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" d.Key("i")?=?"it" Response.Write("The?key?i?has?been?set?to?it,?and?the?value?is:?"?&?d.Item("it")) set?d=nothing %> </body> </html>
返回鍵/項目對的數(shù)量
本例演示如何使用 Count 屬性來返回鍵/項目對的數(shù)量。
<!DOCTYPE?html> <html> <body> <% dim?d,?a,?s,?i set?d=Server.CreateObject("Scripting.Dictionary") d.Add?"n",?"Norway" d.Add?"i",?"Italy" Response.Write("The?number?of?key/item?pairs?is:?"?&?d.Count) set?d=nothing %> </body> </html>