
我正在嘗試訪問此陣列中的 recipeIngredient。
我試過這個:
<cfloop from="1" to="#ArrayLen(contents)#" index="i">
<cfoutput>
#i.recipeIngredient#<br>
</cfoutput>
</cfloop>
我收到錯誤訊息“您已嘗試將型別為coldfusion.runtime.Array 的標量變數取消參考為具有成員的結構。”
uj5u.com熱心網友回復:
您正在使用嵌套資料,因此您需要檢查是否存在具有recipeIngredient輸出它的鍵的特定結構。
在這種情況下,我不會按index迭代陣列,因為 CFML 通過使用屬性陣列并按其items迭代它為 cfloop 陣列提供了極好的可能性,這感覺更自然且更易于閱讀。
此外,不要添加<cfoutput>到回圈的內部主體,因為它會增加 cfengine 的開銷。相反,使用 cfoutput 包含回圈。
<cfoutput>
<cfloop array="#contents#" item="item">
<cfif isStruct( item ) and structKeyExists( item, "recipeIngredient")>
<cfloop array="#item.recipeIngredient#" item="ingredient">
#ingredient#<br>
</cfloop>
</cfif>
<!--- for looping over a struct like recipeinstructions use collection attribute--->
<cfif isStruct( item ) and structKeyExists( item, "recipeinstructions")>
<cfloop collection="#item.recipeinstructions#" item="key">
Value for key '#encodeForHTML(key)#': #encodeForHTML( item.recipeinstructions[key])#<br>
</cfloop>
</cfif>
</cfloop>
</cfoutput>
uj5u.com熱心網友回復:
另一種回圈方式是使用index回圈而不是array回圈或collection回圈然后從 1 回圈到arrayLen()陣列的第 1 位。無論哪種方式都很好。我通常更喜歡這種方法,因為在訪問更深的嵌套級別結構和陣列時更容易閱讀。如果您選擇使用它,您可以按如下方式重構您的代碼。如果你想看看,我在這里創建了一個作業演示。
<cfoutput>
<h4>Ingredients</h4>
<cfloop index="i" from="1" to="#arrayLen(contents['recipeIngredient'])#">
#contents['recipeIngredient'][i]# <br>
</cfloop>
<h4>Instructions</h4>
<cfloop index="i" from="1" to="#arrayLen(contents['recipeInstructions'])#">
#contents['recipeInstructions'][i]['@type']# <br>
#contents['recipeInstructions'][i]['name']# <br>
#contents['recipeInstructions'][i]['text']# <br>
#contents['recipeInstructions'][i]['url']# <br>
#contents['recipeInstructions'][i]['image']# <br>
<br>
</cfloop>
</cfoutput>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470168.html
