首页 > 解决方案 > ColdFusion 循环遍历具有空/未定义字段的数组

问题描述

我正在从我们的供应商之一的 API 下载数据。数据是一个数组,但有些字段是空的,并以undefined. 我可以通过循环获取大部分信息,但是当我添加“注释”字段时,它会失败并出现以下错误:

“元素注释在作为表达式的一部分引用的 CFML 结构中未定义。包含或处理的文件的特定顺序是:

C:\websites\Fire\Reports\xml_parse\Crewsense_payroll_loop.cfm,第 21 行

当我查看转储时,我看到该字段显示为“未定义”。我已经没有想法了。任何帮助将不胜感激。我已经包含了整个代码和一个指向显示数组的转储的链接。

<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>

<cfoutput>

<cfset ApiData = deserializeJSON(result.filecontent)>

<cfset API_ArrayLength = arraylen(ApiData)>

    <cfloop index="i" from="1" to=#API_ArrayLength#>    

    #i# #ApiData[i]["name"]#
        #ApiData[i]["employee_id"]#
        #ApiData[i]["start"]#
        #ApiData[i]["end"]#
        #ApiData[i]["total_hours"]#
        #ApiData[i]["work_type"]#
        #ApiData[i]["work_code"]#
        #ApiData[i]["user_id"]#
        #ApiData[i]["notes"]#  <---Fails here when added--->

        <cfset i = i+1>
    <br>
    </cfloop>   

    <cfdump var="#ApiData#">

</cfoutput>

倾倒

标签: coldfusioncoldfusion-10

解决方案


在处理具有可选元素的数据结构时,您需要在尝试访问它们之前检查它们的存在。否则你会得到那个错误。作为示例,我在您的代码中添加了一个使用structKeyExists()if函数的条件片段。

<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>

<cfoutput>

    <cfset ApiData = deserializeJSON(result.filecontent)>

    <cfset API_ArrayLength = arraylen(ApiData)>

    <cfloop index="i" from="1" to=#API_ArrayLength#>    

    #i# #ApiData[i]["name"]#
        #ApiData[i]["employee_id"]#
        #ApiData[i]["start"]#
        #ApiData[i]["end"]#
        #ApiData[i]["total_hours"]#
        #ApiData[i]["work_type"]#
        #ApiData[i]["work_code"]#
        #ApiData[i]["user_id"]#
        <cfif structKeyExists(ApiData[i],"notes")>
            #ApiData[i]["notes"]#  <!--- Show 'notes' if it exists --->
        <cfelse>
            'notes' is not available  <!--- Do something here (or not) --->
        </cfif>

        <cfset i = i+1>
        <br>
    </cfloop>   

    <cfdump var="#ApiData#">

</cfoutput>

推荐阅读