在遍历记录集时从数组项分配属性

Assigning an atribute from an array item while looping through a recordset

我在记录集上使用循环来生成 JSON(工作正常)但我需要从数组中分配一个自定义 class,每次如果记录集中的项目多于数组中的项目,循环将继续然后重新开始。

这是我的代码:

    cnArray=array("Blue", "Magenta", "DarkViolet", "Red", "Orange", "Green", "Yellow", "Turq", "MidBlue")
'//that's my array of custom class names

    AjaxSQL="SELECT Title,StartDate,EndDate FROM TBL;"
    set AjaxRS=Myconn.execute(AjaxSQL)
    set AjaxSQl=nothing
'//that's my recordset set up

    classname=cnArray(0)
'// specifying the first item in the array to be my variable name which will be used in the loop

    AjaxJSON="["
    Do while not AjaxRS.eof
        AjaxJSON=AjaxJSON&"{'start': '"&AjaxRS("StartDate")&"', 'end': '"&AjaxRS("EndDate")&"', 'content': '"&AjaxRS("Title")&"', 'className': '"&classname&"'},"
        AjaxRS.MoveNext
    loop
    AjaxJSON=left(AjaxJSON,(len(AjaxJSON)-1))
    AjaxJSON=AjaxJSON&"]"
    response.write(replace(AjaxJSON,"'",""""))
'// the loop that generates the JSON

正如我所说,循环工作正常,JSON 有效但我无法弄清楚如何使 classname 变量更改为数组中的下一个然后重启。

任何想法都非常受欢迎(在 SQL 电话会议上讨论是否这样做)

谢谢

elboffor

::编辑::

根据要求,下面是我当前的 JSON 的样子:

[{
    "start": "/Date(1466553600000)/",
    "end": "/Date(1466985600000)/",
    "content": "test",
    "className": "Blue"
}, {
    "start": "/Date(1467244800000)/",
    "end": "/Date(1467244800000)/",
    "content": "Pennyroyal Tea",
    "className": "Blue"
}]

我希望它看起来像这样:

[{
    "start": "/Date(1466553600000)/",
    "end": "/Date(1466985600000)/",
    "content": "test",
    "className": "Blue"
}, {
    "start": "/Date(1467244800000)/",
    "end": "/Date(1467244800000)/",
    "content": "Pennyroyal Tea",
    "className": "Magenta"
}]

如您所见,第二个响应应该是数组的第二次迭代,随着更多的添加,它将遍历数组直到到达 MidBlue,然后用 Blue

再次启动数组

试试这个:

    cnArray=array("Blue", "Magenta", "DarkViolet", "Red", "Orange", "Green", "Yellow", "Turq", "MidBlue")
    cnTotal=UBound(cnArray)+1
    AjaxSQL="SELECT Title,StartDate,EndDate FROM TBL;"
    set AjaxRS=Myconn.execute(AjaxSQL)
    set AjaxSQl=nothing

    cnIndex = 0
    AjaxJSON="["
    Do while not AjaxRS.eof
        AjaxJSON=AjaxJSON&"{'start': '"&AjaxRS("StartDate")&"', 'end': '"&AjaxRS("EndDate")&"', 'content': '"&AjaxRS("Title")&"', 'className': '"&cnArray(cnIndex Mod cnTotal)&"'},"
        AjaxRS.MoveNext
        cnIndex = cnIndex + 1
    loop
    AjaxJSON=left(AjaxJSON,(len(AjaxJSON)-1))
    AjaxJSON=AjaxJSON&"]"
    response.write(replace(AjaxJSON,"'",""""))

使用 cnIndex 计数器变量和 Mod 运算符可以获取必要的元素。当 cnIndex 递增时,Mod 运算符将计数器 cnIndex 除以数组中元素的数量 cnTotal 和 returns 余数,余数始终在 0 和最后一个之间数组元素索引。