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
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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.