mrt*_*181 3 arrays coldfusion loops
我有以下数组.
<cfset ItemHasUsers = arrayNew(1)>
<cfloop query="qReadData">
<cfset ItemHasUsers[qReadData.currentrow]["ID"] = qReadData.ID >
<cfset ItemHasUsers[qReadData.currentrow]["Asset"] = qReadData.COUNTOFITEMS >
</cfloop>
Run Code Online (Sandbox Code Playgroud)
我从我的数据库中获取了一些记录,这些记录放入表中并通过表单进行操作.
<form action="same-site.cfm method="post">
<table>
<tr>
<th>ID</th>
<th>Asset</th>
<th>Delete</th>
<tr>
<cfset ItemHasUsers = Item.getItemHasUsers() >
<cfoutput>
<cfloop index="i" from="1" to="#arrayLen(ItemHasUsers)#">
<td>#ItemHasUsers[i]["ID"]#</td>
<td><input type="text" name="upd_#ItemHasUsers[i]["ID"]#" maxlength="6" size="6" value="#ItemHasUsers[i]["Asset"]#"></td>
<td><input type="checkbox" name="del_#ItemHasUsers[i]["ID"]#"></td>
</tr>
</cfloop>
</cfouput>
</table>
<input type="submit" value="OK">
</form>
Run Code Online (Sandbox Code Playgroud)
依赖我的输入我想更新我的数据库.目前我循环通过表单结构来清除我想要删除的用户.看起来很丑,但我不知道更好的方法 - >看初学者标签;)
<cfset ItemHasUsers = Item.getItemHasUsers() >
<cfloop collection="#form#" item="key">
<cfif left(key,len("DEL_")) eq ("DEL_")>
<cfset Id = listLast(key,"_") >
<cfloop index="i" from="1" to="#arrayLen(ItemHasUsers)#">
<cfif ItemHasUsers[i]["ID"] eq Id>
<cfset structClear(ItemHasUsers[i]) >
</cfif>
</cfloop>
</cfif>
</cfloop>
<cfset ItemHasUsers = Item.getItemHasUsers() >
<cfloop index="i" from="1" to="#arrayLen(ItemHasUsers)#">
<cfif ItemHasUsers[i]["ID"] eq Id>
<cfset arrayDeleteAt(ItemHasUsers,i) >
</cfif>
</cfloop>
Run Code Online (Sandbox Code Playgroud)
仅当我检查输入表单中的最后一个元素以进行删除时,此方法才有效.如果我检查任何其他我得到以下错误
无法找到数组变量"ITEMHASUSERS"的第1维3号位置的元素.
好的,arrayDeleteAt调整数组大小并自动删除间隙.如何更新下一次迭代的循环长度?
这样做的诀窍是向后逐步执行数组.从最后一个元素开始并循环到第一个元素,这样,在从数组中删除一个项目之后,您将不会尝试引用超过数组长度的元素.
<cfset ItemHasUsers = Item.getItemHasUsers() >
<cfloop index="i" from="#arrayLen(ItemHasUsers)#" to="1" step="-1">
<cfif ItemHasUsers[i]["ID"] eq Id>
<cfset arrayDeleteAt(ItemHasUsers,i) >
</cfif>
</cfloop>
Run Code Online (Sandbox Code Playgroud)