亚当有正确的上下文,但他的代码片段是错误的。
一个可行的功能是:
<cffunction name="$createNestedParamStruct" returntype="struct" access="public" output="false">
<cfargument name="params" type="struct" required="true" />
<cfscript>
var loc = {};
for(loc.key in arguments.params)
{
if (Find("[", loc.key) && Right(loc.key, 1) == "]")
{
// object form field
loc.name = SpanExcluding(loc.key, "[");
// we split the key into an array so the developer can have unlimited levels of params passed in
loc.nested = ListToArray(ReplaceList(loc.key, loc.name & "[,]", ""), "[", true);
if (!StructKeyExists(arguments.params, loc.name))
arguments.params[loc.name] = {};
loc.struct = arguments.params[loc.name]; // we need a reference to the struct so we can nest other structs if needed
loc.iEnd = ArrayLen(loc.nested);
for(loc.i = 1; loc.i lte loc.iEnd; loc.i++) // looping over the array allows for infinite nesting
{
loc.item = loc.nested[loc.i];
if (!StructKeyExists(loc.struct, loc.item))
loc.struct[loc.item] = {};
if (loc.i != loc.iEnd)
loc.struct = loc.struct[loc.item]; // pass the new reference (structs pass a reference instead of a copy) to the next iteration
else
loc.struct[loc.item] = arguments.params[loc.key];
}
// delete the original key so it doesn't show up in the params
StructDelete(arguments.params, loc.key, false);
}
}
</cfscript>
<cfreturn arguments.params />
</cffunction>
我在我的应用程序(CFWheels 之外)中对其进行了测试,它运行良好。您所做的只是传递一个包含应该是结构的结构(在我的情况下是来自 FW/1 的 Rc 结构),但显示为字符串,您将返回一个具有嵌套结构的结构。
例子:
<cfscript>
Struct['hello[world]'] = 1;
Struct['hello[earth]'] = 2;
myhello = $createNestedParamStruct(Struct);
/* Now myhello equals this:
myhello.hello.world = 1;
myhello.hello.eath = 2;
*/
</cfscript>