如何遍历结构数组并显示所有键值 [英] How to loop over array of structures and display all key values

查看:111
本文介绍了如何遍历结构数组并显示所有键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历结构数组,并尝试分配和存储所有键值。如果我将内部循环包装在< cfoutput> 中,则会收到错误消息:无法将复杂对象类型转换为简单值。如果我把它遗漏了,那就行不通了。我缺少什么?

I am looping over an array of structures and trying to assign and store all key values. If I wrap inner loop in <cfoutput>, I am getting an error: "Complex object types cannot be converted to simple values". If I leave it out, then it does not work. What am I missing?

<cfif isJSON(httpResp.fileContent)>
    <cfset jsonData = deserializeJSON(httpResp.fileContent) />    

    <cfloop from="1" to="#arrayLen(jsonData)#" index="i">
        <cfset data = jsonData[i]>

        <!---<cfoutput>--->                 
        <cfloop collection="#data#" item="key">
            #key#:#data[key]#<br>
        </cfloop>       
        <!---</cfoutput>---> 

    </cfloop>

    <cfdump var="#jsonData#">

<cfelse>
      Did not receive a valid Json object
</cfif>

这是输出:

#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#
#key#:#data[key]#


推荐答案


试图分配和存储所有键值

trying to assign and store all key values

如果最终目的是操纵和/或存储,则可以从技术上动态输出所有键值,那么动态循环可能不是您想要的。要提取特定值,只需使用点符号显式引用键名称即可。例如:

While you could technically output all of the keys dynamically, if the ultimate goal is to manipulate and/or store the values, then dynamic looping probably isn't what you want anyway. To extract specific values, just reference the keys names explicitly - using dot-notation. For example:

<cfloop array="#jsonData#" index="prop">
    <cfoutput>
        <hr>confirmation = #prop.confirmation#
        <br>id = #prop.id#
        <br>label.carrier = #prop.label.carrier#
        <br>label.tracking = #prop.label.tracking#
        <br>order.created_at = #prop.order.created_at#
        <br>policy.logistic_code = #prop.policy.logistic_code#
        <br>policy.refund_code = #prop.policy.refund_code#
        <br>ref.order = #prop.ref.order#
        <br>state = #prop.state#
        ... 
    </cfoutput>
</cfloop>

但是,要回答您的问题,错误消息仅表示 cfoutput 只能处理简单值。由于您尝试显示的某些值实际上是结构(即复杂对象),例如 label states cfoutput 会在尝试输出它们时造成阻塞。

However, to answer your question, the error message just means that cfoutput can only handle simple values. Since some of the values you're trying to display are actually structures (i.e. complex objects), like label and states, the cfoutput chokes when it tries to output them.

这篇关于如何遍历结构数组并显示所有键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆