按字符串数组中的唯一索引对值进行分组

Grouping Values by Unique Index in a String Array

如何只检索此示例的唯一数组。

"58|270,58|271,58|272,59|270,59|271,59|272"

我希望这个数组像这样存储:

"58,270,271,272|59,270,271,272"

有人可以在 ASP 经典或 VB 脚本中帮助我吗

从数组中获取唯一项的常用方法是将它们作为键放入 Dictionary:

a = Array(58, 270, 271, 272, 270, 271, 272)

Set d = CreateObject("Scripting.Dictionary")
For Each i In a
  d(i) = True   'value can be anything, relevant is using i as key
Next

WScript.Echo Join(d.Keys, ",")  'Output: 58,270,271,272

这不是一个直截了当的问题,我发现自己思考了几分钟才终于想到了解决方法。

要从指定的输入中生成输出,需要某种自定义反序列化/序列化方法。下面的代码创建一个二维数组,它将包含唯一索引 (58、59 等) 并用逗号分隔的关联值列表 填充它们(完成它像这样使连载变得容易).

从结构上看,反序列化后看起来像这样

----- Array Debug ------
data(0, 0) = 58
data(1, 0) = 270,271,272
data(0, 1) = 59
data(1, 1) = 270,271,272

然后我们以此为基础以所需格式构建序列化字符串。

'Function takes string input in the form <index>|<value>, ... extracts
'them into a 2D array groups duplicate indexes together.
Function DeserialiseToCustomArray(str)
  Dim a1, a2, x, y, idx
  If Len(str & "") > 0 Then
    a1 = Split(str, ",")
    ReDim data(1, 0)
    For x = 0 To UBound(a1)
      a2 = Split(a1(x), "|")
      If IsArray(data) Then
        idx = -1
        'Check for duplicates
        For y = 0 To UBound(data, 2)
          If data(0, y) = a2(0) Or IsEmpty(data(0, y)) Then
            idx = y
            Exit For
          End If
        Next

        'No duplicate found need to add a new element to the array.
        If idx = -1 Then
          idx = UBound(data, 2) + 1
          ReDim Preserve data(1, idx)
        End If
        data(0, idx) = a2(0)
        If IsEmpty(data(1, idx)) Then
          data(1, idx) = a2(1)
        Else
          data(1, idx) = Join(Array(data(1, idx), a2(1)), ",")
        End If
      End If
    Next
  End If
  DeserialiseToCustomArray = data
End Function

'Function takes a 2D array built from DeserialiseToCustomArray() and
'serialises it into a custom string in the form <index>,<value>, ... | ...
Function SerialiseArray(data)
  Dim x, y
  Dim str: str = Empty
  If IsArray(data) Then
    For y = 0 To UBound(data, 2)
      If y > 0 And y <= UBound(data, 2) Then str = str & "|"
      str = str & data(0, y) & "," & data(1, y)
    Next
  End If
  SerialiseArray = str
End Function

几个用法示例:

Dim str: str = "58|270,58|271,58|272,59|270,59|271,59|272"
Dim data, result

data = DeserialiseToCustomArray(str)
result = SerialiseArray(data)
WScript.Echo "input: " & str
WScript.Echo "output: " & result

输出:

Result: 58,270,271,272|59,270,271,272
Dim str: str = "58|270,58|271,58|272,59|270,59|271,59|272,60|345,61|345,58|270,60|200"
Dim data, result

data = DeserialiseToCustomArray(str)
result = SerialiseArray(data)
WScript.Echo "input: " & str
WScript.Echo "output: " & result

输出:

Result: 58,270,271,272,270|59,270,271,272|60,345,200|61,345

Note: If using these examples in Classic ASP remove the WScript.Echo and replace with Response.Write.