检查结构中是否存在密钥 [英] Checking for key existence in structure
问题描述
我有一个名为 #cfData#
的变量,其中包含结构数组。从图像中可以清楚地看到,第一个结构数组有6个键,而第二个结构只有两个键,即日期和打开。
I have a variable named #cfData#
which contains an array of structures. As it's clear from the image, for 1st structure array there are 6 keys and for 2nd, only two keys,viz date and open.
如果我运行一个通用循环,则需要遍历每一个键,第二个数组元素将出现错误。因此,只有当所有键都存在于结构中时,以下命令才起作用:
If I run a common loop, to go through each and every key, I will get an error at second array element. So the following only works when all the keys are present in the structure:
<cfset blockedtotal = 0 />
<cfset bouncetotal = 0 />
<cfset blocked = 0/>
<cfset datetotal = 0 />
<cfloop array = #cfData# index = "i">
<cfset blockedtotal += i.blocked />
<cfset bouncetotal += i.bounce />
</cfloop>
在线阅读后,我有了使用StructKeyExists的想法,我认为我可以按照以下方式进行:
After reading online, I got an idea of using StructKeyExists where I think I can proceed in the following way:
<cfif structKeyExists(cfData,"bounce")>
<cfoutput>Bounce:#cfData.bounce#"/></cfoutput>
<cfelse>
<cfoutput> Bounce : [none]<br/></cfoutput>
</cfif>
但是我想知道在哪里我到底应该在cfloop中插入上面的代码吗?请告知我的方法是否错误。
But I am wondering, where exactly should I insert the above code inside the cfloop? Please advise if my approach is wrong.
更新:
谢谢大家,我根据答案使用以下代码来运行它,并且运行良好:
Thanks guys. I got it running by using the following code based on the answers and it's running fine:
<cfloop array="#cfData#" index="i">
<cfif structKeyExists(i, "date")>
<cfset counter++>
<cfoutput>#counter#</cfoutput> Date is: <cfoutput> #i.date#</cfoutput> <br/>
</cfif>
</cfloop>
推荐答案
您不需要您可以使用
<cfloop array="#cfData#" index="i">
<cfloop collection="#i#" item="key">
struct with key '#key#' has data: #i[key]#
</cfloop>
</cfloop>
Of,如果您需要确定结构是否具有某些键,请执行以下操作:
Of, if you need to decide if the struct has certain key, do something:
<cfloop array="#cfData#" index="i">
<cfif structKeyExists(i, "someKey")>
<cfset counter++>
</cfif>
</cfloop>
这篇关于检查结构中是否存在密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!