我试图从基于搜索字符串的coldfusion中的多维数组中删除元素(位置1与我的搜索字符串匹配时的完整数组)。我想出了以下内容,它可以工作(此处数组中的第二个元素被删除),但是它出错了,因为它弄乱了索引 - 当数组的长度为n-1时,它会尝试检查第n个元素删除。
<cfset Profiles =
[
["aaa", "xdg", "123", "xyz", "ggg" ],
["bbb", "xwa", "234", "xyz", "fff" ],
["ccc", "xed", "567", "xyz", "eee" ],
["ddd", "xae", "789", "xyz", "hhh" ],
["eee", "xsr", "901", "xyz", "bbb" ],
["fff", "xdg", "902", "xyz", "jjj" ]
]/>
<cfset CheckFor = "bbb" />
<cfset Position = 1 />
<cfloop array="#Profiles#" index="arrayIndex" >
ArrayFind: #arrayFind( arrayIndex, CheckFor )#<br />
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
</cfif>
<cfset Position++ />
</cfloop>
<cfdump var="#DocumentProfiles#" />
答案 0 :(得分:1)
改变这个:
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
</cfif>
<cfset Position++ />
到此:
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
<cfelse>
<cfset Position++ />
</cfif>
答案 1 :(得分:1)
如果你是ACF10 +,而不是显式循环,你可以这样做:
<cfscript>
Profiles = [
["aaa","bbb","asdf"]
, ["bbb","asdf","asdfasfs"]
, ["ccc","dfhgasdfg","bbb"]
, ["bbb","asdfasdf","Aasdfa"]
] ;
checkfor = "bbb" ;
//// FROM HERE ////
arrayEach(
Profiles,
function(obj){
obj[1]==checkfor?arrayDelete(Profiles,obj):'';
}
);
//// TO HERE ////
WriteDump(Profiles);
</cfscript>
编辑:或者更好,没有循环。仍然是ACF10 +,但也适用于Lucee。
p2 = arrayFilter( Profiles, function(obj){ return obj[1] != checkfor ; } );