Search Thru a Multi-Dimensional Array

I ran into a situation today where I needed to search thru a multi-dimensional array to update quantities and total prices for backordered products coming from a query. Unfortunately ColdFusion doesn't have an ArrayFind() function like it does for structs. I did a search on CFLib and found a UDF that did the trick.

The ArrayFindByDimension() UDF allows you to pass it an array, the value to find, dimension to search and returns the numeric array position if found, 0 if not found.

Here is some of my sample code:

<!---
Search a multidimensional array for a value.

@param arrayToSearch     Array to search. (Required)
@param valueToFind     Value to find. (Required)
@param dimensionToSearch     Dimension to search. (Required)
@return Returns a number.
@author Grant Szabo (grant@quagmire.com)
@version 1, September 23, 2004
--->

<cffunction name="ArrayFindByDimension" access="public" returntype="numeric" output="false">
   <cfargument name="arrayToSearch" type="array" required="Yes">
   <cfargument name="valueToFind" type="string" required="Yes">
   <cfargument name="dimensionToSearch" type="numeric" required="Yes">
   <cfscript>
      var ii = 1;
      
      //loop through the array, looking for the value
      for(; ii LTE arrayLen(arguments.arrayToSearch); ii = ii + 1){
         //if this is the value, return the index
         if(NOT compareNoCase(arguments.arrayToSearch[ii][arguments.dimensionToSearch], arguments.valueToFind))
            return ii;
      }
      //if we've gotten this far, it means the value was not found, so return 0
      return 0;
   </cfscript>
</cffunction>

<!--- begin the count --->
<cfset i = 1>
<!--- create the array --->
<cfset products = ArrayNew(2)>

<cfloop query="backordered">
   <!--- search array --->
   <cfset arrPos = arrayFindByDimension(products, "#backordered.product_code#", 2)>
   <cfif arrPos EQ 0>
      <cfset products[i][1] = backordered.product_id>
      <cfset products[i][2] = backordered.product_code>
      <cfset products[i][3] = backordered.order_details_quanity>
      <cfset products[i][4] = backordered.order_details_price * backordered.order_details_quanity>
      <cfset i = i + 1>
   <cfelse>
      <cfset products[arrPos][3] = products[arrPos][3] + backordered.order_details_quanity>
      <cfset products[arrPos][4] = products[arrPos][4] + (backordered.order_details_price * backordered.order_details_quanity)>
   </cfif>
</cfloop>

<!--- dump the array --->
<cfdump var="#products#">

No comments yet.

(will not be published)
Leave this field empty: