Jump to content

How To Sum Certain Array Values?


anevins

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?

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

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.