ListToStruct( strList, strDelimiter1, strDelimiter2 )
Downloadable Files
listtostruct_function.cfm.txt ( 3,498 Bytes )
This uses the ListToStruct() function to parse out a dual-delimited list ( such as a query string with & and = delimiters ) into an equivalent key-value struct. While values are not required, pairs with no key value are not added to the struct.
<cffunction name="ListToStruct" access="public" returntype="struct" output="no"
hint="This takes a list and breaks it up into key-value pairs. Its takes two delimiters, one for the pair sepparation, and one for the key-value sepparation.">
<!--- Define arguments. --->
<cfargument name="List" type="string" required="true" />
<cfargument name="Delimiter1" type="string" required="true" />
<cfargument name="Delimiter2" type="string" required="true" />
<cfscript>
// Declare the local scope.
var LOCAL = StructNew();
// Build the resultant struct.
LOCAL.Result = StructNew();
// Place each delimiter with a space around it to ensure that
// each part of the list will show up in our list-to-array calls.
ARGUMENTS.List = REReplace(
ARGUMENTS.List,
"([\#ARGUMENTS.Delimiter2#\#ARGUMENTS.Delimiter2#]{1})",
" \1 ",
"ALL"
);
// Get the array of pairs.
LOCAL.Pairs = ListToArray( ARGUMENTS.List, ARGUMENTS.Delimiter1 );
// Loop over the pairs array to break out the key-value data.
for ( LOCAL.PairIndex = 1 ; LOCAL.PairIndex LTE ArrayLen( LOCAL.Pairs ) ; LOCAL.PairIndex = (LOCAL.PairIndex + 1)){
// Get this pairs.
LOCAL.Pair = ListToArray(
LOCAL.Pairs[ LOCAL.PairIndex ],
ARGUMENTS.Delimiter2
);
// Check to make sure that we have two items in this pair.
if (ArrayLen( LOCAL.Pair ) EQ 2){
/
// Get the key and the value. Trim both values to take away
// the effects of adding spaces earlier.
LOCAL.Key = Trim( LOCAL.Pair[ 1 ] );
LOCAL.Value = Trim( LOCAL.Pair[ 2 ] );
// Make sure we have a key length.
if (Len(LOCAL.Key)){
// Add the pair to the resultant struct.
LOCAL.Result[ LOCAL.Key ] = LOCAL.Value;
}
}
}
// Return the resultant struct that may or may not have
// any keys in it.
return( LOCAL.Result );
</cfscript>
</cffunction>
Added April 23, 2006 / Updated April 23, 2006



