1

我想显示结构键的值,例如:

   #stReviewDetail['tags']['travelParty']['value']#

有可能tagstravelPartyvalue缺失。检查结构层次结构是否可用的最佳方法是什么?就像是:

<cfif StructKeyExists(stReviewDetail, 'tags') AND 
      StructKeyExists(stReviewDetail['tags'], 'travelParty') AND 
      StructKeyExists(stReviewDetail['tags']['travelParty'], 'value') >
    ....
</cfif>

还是有更好的方法来做到这一点?

4

2 回答 2

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>
于 2012-12-17T16:38:47.793 回答
2

如果您知道特定的键,则可以使用isDefined

<cfif isDefined("stReviewDetail.tags.travelParty.value")>
    <cfdump var="#stReviewDetail.tags#">    
</cfif>
于 2012-12-17T16:58:12.557 回答