Jump to content

Adding up array values by email


beanymanuk

Recommended Posts

Hi

 

I am gathering numbers in an array and then want to add together all the numbers attached to the same email so I end up with the Grand totals of each email address.

 

Below is the code I am using to pull out the email and attached values

$getcashdonationsdb = $wpdb->get_results("SELECT * FROM cashdepo WHERE cause='$causename' AND status='2' ORDER BY user DESC");
$i = 0;
while($i < $count2) {
foreach($getcashdonationsdb as $getcashdonationsdb){
	$dataa[$i]['email'] = $getcashdonationsdb->email;
                $dataa[$i]['cost'] = $getcashdonationsdb->cost;
         }
}

 

Anyone have any suggestions how I can achieve this most efficiently.

Link to comment
https://forums.phpfreaks.com/topic/254343-adding-up-array-values-by-email/
Share on other sites

Well, for starters, I would suggest not using '*' in your select statement. Just include the fields you need. In this case it looks like you want the email and cost fields. Secondly, why are you using "ORDER BY user" if you are not using that for any purpose? Seems like you would have wanted to ORDER BY email. Anyway, if you do not need the granular data (i.e. each email and cost record) then you don't need to add up the values in the array. Instead, change your query to get the summed values for you:

 

SELECT email, SUM(cost) as total_cost
FROM cashdepo
WHERE cause='$causename'
  AND status='2'
GROUP BY email

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.