Coldfusion How can i detect duplicate variable in array

318 Views Asked by At

There is a loop I pulled from the database with cfloop. After transferring this loop to arrays, I want to increase the number of stocks if the same array exists.

<cfoutput query="getStocks">
    <cfif #CurrentRow# lt 5> 
        <cfscript>
            c=#CurrentRow#;
            if (c==1){
                arr[c]['stok_kod']='#STOCK_CODE#';
                arr[c]['lot']='#LOT_NO#';
                arr[c]['stok']=#STOK_MIKTARI#;
                arr[c]['depo']='#DEPO#';
                arr[c]['isim']='#PRODUCT_NAME#';
                arr[c]['skt']='#GET_SKT.DELIVER_DATE#';
            }
            for (i=1; i <= arrayLen(#arr#);i++) {
                if (arr[i]['stok_kod'] eq '#STOCK_CODE#' ){
                    arr[i]['stok']+=#STOK_MIKTARI#;
                }else{
                    arr[c]['stok_kod']='#STOCK_CODE#';
                    arr[c]['lot']='#LOT_NO#';
                    arr[c]['stok']=#STOK_MIKTARI#;
                    arr[c]['depo']='#DEPO#';
                    arr[c]['isim']='#PRODUCT_NAME#';
                    arr[c]['skt']='#GET_SKT.DELIVER_DATE#';
                }
            }
        </cfscript>
    </cfif>
</cfoutput>

enter image description here

How can I detect those with the same stock code?

2

There are 2 best solutions below

0
Khoa Nguyen On

You can try to use query of queries method with GROUP BY function

Here is the example how it works.

<cfscript>
    getStocks = queryNew("stok_kod,stok", "varchar,integer");
    queryAddRow(getStocks);
    querySetCell(getStocks, "stok_kod", "1234");
    querySetCell(getStocks, "stok", "-10");
    queryAddRow(getStocks);
    querySetCell(getStocks, "stok_kod", "5678");
    querySetCell(getStocks, "stok", "10");
    queryAddRow(getStocks);
    querySetCell(getStocks, "stok_kod", "1234");
    querySetCell(getStocks, "stok", "30");
</cfscript>

<cfquery name="newQuery" dbtype="query">
  SELECT stok_kod, SUM(stok) as stok
  FROM getStocks
  GROUP BY stok_kod
</cfquery>

<cfdump var="#newQuery#">

OUTPUT

Result output

0
akashb On

I'd suggest you have one variable that will have the list of your distinct stock codes.

Example: <cfset lst_stok_kod = "a,b,c,d"> Perhaps from your SQL query.

After that, you could use the ArrayFindNoCase function to check if your array has that stock code present or not. If you find it more than once, you increase the number of stocks each time.