Jump to content

Recommended Posts

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 by anevins
Link to comment
https://forums.phpfreaks.com/topic/271262-how-to-sum-certain-array-values/
Share on other sites

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

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 by Christian F.
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.