我想显示结构键的值,如:
#stReviewDetail['tags']['travelParty']['value']#
tags
,travelParty
或value
可能会丢失。检查结构层次结构是否可用的最佳方法是什么?类似的东西:
<cfif StructKeyExists(stReviewDetail, 'tags') AND
StructKeyExists(stReviewDetail['tags'], 'travelParty') AND
StructKeyExists(stReviewDetail['tags']['travelParty'], 'value') >
....
</cfif>
还是有更好的方法吗?
答案 0 :(得分:5)
多个StructKeyExists是丑陋的,编写一个函数来简化这个很容易:
<强>用法:强>
<cfif CheckNestedKeys(stReviewDetail,['tags','travelParty','value']) >
#stReviewDetail['tags']['travelParty']['value']#
</cfif>
的代码:强>
<cffunction name="CheckNestedKeys" returntype="Boolean" output=false>
<cfargument name="Struct" type="Struct" required />
<cfargument name="Keys" type="Array" required />
<cfset var CurStruct = Arguments.Struct />
<cfloop index="local.CurKey" array=#Arguments.Keys# >
<cfif StructKeyExists(CurStruct,CurKey)>
<cfset CurStruct = CurStruct[CurKey] />
<cfelse>
<cfreturn false />
</cfif>
</cfloop>
<cfreturn true />
</cffunction>
答案 1 :(得分:2)
如果你知道具体的密钥,可以使用isDefined
:
<cfif isDefined("stReviewDetail.tags.travelParty.value")>
<cfdump var="#stReviewDetail.tags#">
</cfif>