anevins Posted November 27, 2012 Share Posted November 27, 2012 (edited) Hi all, What I'm trying to do is get the average of sentiment values for each City in the UK. I have an array of all the cities in the UK, with sentiment values for each city. -- Tricky to say, sorry -- Cities can appear more than once, so I want to find the average sentiment for that city, then construct/ return an array with just those cities and their sentiment (that has been averaged for all occurrences of that city). This is an excerpt of my array array (size=1871) 0 => array (size=2) 'name' => string 'Cardiff' (length=7) 'sentiment' => string '2.72' (length=4) 1 => array (size=2) 'name' => string 'London' (length=6) 'sentiment' => string '4.24' (length=4) 2 => array (size=2) 'name' => string 'Birmingham' (length=10) 'sentiment' => string '3.415' (length=5) 3 => array (size=2) 'name' => string 'Birmingham' (length=10) 'sentiment' => string '3.34' (length=4) and so forth. With Birmingham, for example, I want to add up 3.415 with 3.34, divide by 2 and then return just the one occurrence of "Birmingham" and its averaged sentiment. I want to do this for each city, so there is only one occurrence for each city, in another array. Does anyone know how I might go about this? Edited November 27, 2012 by anevins Quote Link to comment https://forums.phpfreaks.com/topic/271262-how-to-sum-certain-array-values/ Share on other sites More sharing options...
requinix Posted November 27, 2012 Share Posted November 27, 2012 First step I would take is building up an array that looked like array( "Cardiff" => array( "total" => 2.72, "count" => 1 ), "London" => array( "total" => 4.24, "count" => 1 ), "Birmingham" => array( "total" => 6.755, "count" => 2 ) ) Quote Link to comment https://forums.phpfreaks.com/topic/271262-how-to-sum-certain-array-values/#findComment-1395703 Share on other sites More sharing options...
Christian F. Posted November 27, 2012 Share Posted November 27, 2012 (edited) Is this array fetched from a database somewhere? If so, then you can use the DB to do the calculations for you. Just a quick example: SELECT AVG(`sentiment`), `name` FROM `city_sentiment` GROUP BY `city_id`; Edited November 27, 2012 by Christian F. Quote Link to comment https://forums.phpfreaks.com/topic/271262-how-to-sum-certain-array-values/#findComment-1395733 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.