【问题标题】:ColdFusion looping over an array with an empty/undefined fieldColdFusion 循环遍历具有空/未定义字段的数组
【发布时间】:2019-01-07 04:45:50
【问题描述】:

我正在从我们的供应商之一的 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>

Dump

【问题讨论】:

  • 除了 MiguelF 的 cmets,考虑使用“数组”循环,而不是 from/to,来简化代码

标签: coldfusion coldfusion-10


【解决方案1】:

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

<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>

【讨论】:

  • 为了使这更容易,您可以将可选键添加为列表,然后也循环遍历它,检查每个列表元素,而不是为每个键编写单独的 structKeyExists()。您可以根据需要调整此列表,以减少代码更改。第三个选项将是一个结构数组,因此您可以根据需要列出可选键及其相关默认值。
  • 是的好点@AdrianJ.Moreno。我只是想向 OP 展示如何在访问之前检查结构的基本思想。
猜你喜欢
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2015-09-02
相关资源
最近更新 更多