oggetto Popola con menù multidimensionale
-
10-10-2019 - |
Domanda
Mi chiedo se non v'è un modo efficace per mettere un menu in un array o qualsiasi altro tipo di dati. Con PHP vorrei fare qualcosa di simile:
$menu[1] = "home";
$menu[2] = "news";
$menu[3]["item"] = "products";
$menu[3]["subMenu"][1] = "jackets";
$menu[3]["subMenu"][2] = "T-shirts";
$menu[4] = "contact";
Comunque non ho idea di come si potrebbe fare questo in ColdFusion. Voglio afferrare questi dati dal DB e spingerlo in un oggetto, questo mi permetterà di generare il codice HTML dalla matrice.
Soluzione
In realtà è molto simile. Questo presuppone ColdFusion 8 (o superiore) per matrice ([]
) e struct ({}
) letterali:
<cfset menu = [] /> <!--- Create initial array --->
<cfset menu[1] = "home" />
<cfset menu[2] = "news" />
<cfset menu[3] = {} /> <!--- Create structure --->
<cfset menu[3]["item"] = "products" /> <!--- Address structure by key --->
<cfset menu[3]["subMenu"] = [] />
<cfset menu[3]["subMenu"][1] = "jackets" />
<cfset menu[3]["subMenu"][2] = "T-shirts" />
<cfset menu[4] = "contact" />
<cfdump var="#menu#" /> <!--- Output --->
Speranza che aiuta!
Altri suggerimenti
Per prendere la risposta di Ciaran un passo più in là, si può fare tutto con letterali oggetto in CF 9:
<cfset menu = ["home",
"news",
{"item"="products",
"subMenu"= ["jackets",
"T-shirts"]},
"contact"]>
<cfdump var="#menu#" /> <!--- Output --->
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow