Trimming an array while adding up one "column"

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello group,

Here's is a brief overview of what I'm trying to do, and then the code.
I am building an array from a query that contains value fields and then a count value. Some of these value fields are the same, so I would like to trim the array of any repeating values, while making sure that the array items that contain the counts are added up appropriately. One thing to note is that I can't do this during the initial database query, but only after the initial array has been created.


Here is the meat of the code that builds the initial array (I've slaughtered indention to make it fit better via email):
...
while($row = mssql_fetch_array($result))
{
$subResponses_array[$ctr]["code"] = $row[code];
$subResponses_array[$ctr]["responseCount"] = $row[responseCount];
$ctr++;
}


//To keep the items with the same code type together
$subResponses_array = sortMultiArray($subResponses_array,"code");
return $subResponses_array;
...

Now that I have the larger array I would like to now run through the array, and remove duplicate rows while adding the counts (responseCount).

So if I have:   I am some text | 23
		I am some text | 10

I want: I am some text | 33

Here is the function I am attempting to make work, a function that receives teh array and is supposed to remove duplicate codes/text and create one line, one total for any duplicate set of codes.


function removeAddDuplicates($theArray,$columnCompare,$columnAdd)
{
//$columnCompare is the "column" used to see if values on a line has been repeated
//$columnAdd represents the array item containing the counts, which should
//be increased if two lines are merged.
$ctr=0;
while($ctr < count($theArray))
{
//IF code is the same as the previous code, then just adjust the total count
if ($theArray[$ctr][$columnCompare] == $theArray[$ctr-1]['$columnCompare'])
{
$theArray[$ctr-1][$columnAdd] = $theArray[$ctr-1]['$columnAdd']+$theArray[$ctr]['$columnAdd'];
//Not really used to using unset...in some cases seems to leave blank /lines when printing array before sorting again.
unset($theArray[$ctr]);
}
$ctr++;
}
return $theArray;
}



Thanks for any advice.









-- John Krewson Programmer - SWORPS


-- PHP Database Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux