beanymanuk Posted January 4, 2012 Share Posted January 4, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/254343-adding-up-array-values-by-email/ Share on other sites More sharing options...
Psycho Posted January 4, 2012 Share Posted January 4, 2012 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 Quote Link to comment https://forums.phpfreaks.com/topic/254343-adding-up-array-values-by-email/#findComment-1304154 Share on other sites More sharing options...
beanymanuk Posted January 4, 2012 Author Share Posted January 4, 2012 Thankyou for your help really appreciate it. I totally forgot about GROUP BY silly me. Your solution is totally is exactly what I needed. Quote Link to comment https://forums.phpfreaks.com/topic/254343-adding-up-array-values-by-email/#findComment-1304162 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.