在循环记录集时从数组项中分配属性

时间:2016-06-21 18:55:40

标签: arrays loops vbscript asp-classic recordset

我在记录集上使用循环来生成JSON(工作正常)但是我需要从数组中分配一个自定义类,每次循环继续时将迭代一个,然后如果有更多项则重新启动在记录集中比在数组中。

这是我的代码:

    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启动数组

1 个答案:

答案 0 :(得分:2)

试试这个:

    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中元素的数量,并返回余数,该值始终介于0和最后一个数组元素索引之间。