如何解决基于模式匹配的 Coldfusion 计数
1,2,1
0,2
4,0
1,1
2,1,2
每个数字只能是 0-6。第二步是我的问题所在。我需要计算每个模式。例如,模式 1,1 的计数为 2,因为它出现了两次,而其他模式各只出现一次。
在最后的输出中,我需要能够显示带有计数的每个唯一模式,例如:
1,1 - 2
0,2 - 1
4,0 - 1
2,2 - 1
我正在考虑使用二维数组。哪里
combinations[1][1]="1,1" (the pattern)
combinations[1][2]=2 (the count)
combinations[2][1]="0,2"
combinations[2][2]=1
etc.
如何在匹配模式的同时动态创建数组?即如果尚未找到模式,则将其添加到数组中。如果找到,则添加到计数中。我试过这个:
<cfloop index="i" from="1" to="#ArrayLen(combinations)#">
<cfif not arrayFind(combinations[i][1],"#patterns#")>
<cfset arrayAppend(combinations,["#patterns#",1]) >
<cfelse>
<cfset combinations[i][2] = combinations[i][2] + 1>
</cfif>
</cfloop>
但我在 ArrayFind 上遇到错误:
Object of type class java.lang.String cannot be used as an array
感谢任何帮助。提前致谢。
解决方法
解决了我自己的问题。看起来我用错了函数。这有效:
<cfloop index="i" from="1" to="#ArrayLen(combinations)#">
<cfif Find(combinations[i][1],"#patterns#")>
<cfset combinations[i][2] = combinations[i][2] + 1>
<cfset found = 1>
</cfif>
</cfloop>
<cfif not found>
<cfset arrayAppend(combinations,["#patterns#",1]) >
</cfif>
,
除了使用二维数组,您还可以使用结构体,其中键是模式,值是计数。这自然避免了重复,因为结构的键只能存在一次。
用于创建结构的代码如下所示:
<cfset combinations = {}>
<cfloop query="#dbresults#">
<cfif not structKeyExists(combinations,dbresults.pattern)>
<cfset combinations[dbresults.pattern] = 1>
<cfelse>
<cfset combinations[dbresults.pattern]++>
</cfif>
</cfloop>
最后你只需要遍历结构来输出计数:
<cfloop collection="#combinations#" item="pattern">
<cfoutput><p>#pattern# - #combinations[pattern]#</p></cfoutput>
</cfloop>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。