How to count and sum elements in a multi-dimensional array? - php

i have a array that returns some numbers. and i want to add those numbers together and also count them.
here is what i have so far:
<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
$totalRatings1 = $values['rating'] ;
}
?>
what i am trying to do is to sum the $values['rating'] together and also count them.
So that: $totalRatings = sum_array($values['rating']) and $totalCount = count($values['rating'])
but i get lost in the sintax.
any ideas?
Thanks

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);
$totalRatings = 0;
$totalRated = 0;
foreach ($parsed['data'] as $key => $values){
$totalRatings += (int) $values['rating'];
$totalRated++;
}
?>
$totalRatings will have the aggregated sum of all ratings, $totalRated will be the count of how many ratings there are.

Just declare two variables and then increment them on each iteration:
<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);
$totalRating = 0;
$totalItems = 0;
foreach ($parsed['data'] as $key => $values) {
$totalRating += $values['rating'];
$totalItems++;
}
$totalRating will hold the sum of all rating while $totalItems will contain the total number of items.

Related

How do I cycle through array and multiply every new number with the next?

This is what I have so far:
<?php
$ask_number = readline("Gimme a number?");
$array = Array();
for ($i = 1; $i <= $ask_number; $i++) {
$array[$i] = $i;
}
return 0;
var_dump($sum);
?>
I can get it to ask for a number and create an array.
What I want it to do;
I want it to do this:
1 * 2 * 3 * 4 * 5 * 6.. etc.
Thank you for taking the time to read this!
You can go for range() and foreach()
<?php
$ask_number = 6;//desired number
$array = range(1,$ask_number);//create array
$multiply = 1; //define multiply variable
foreach( $array as $val ){
$multiply *= $val ; // multiple value
}
var_dump($multiply ); // print value
//in case you want sum
var_dump(array_sum($array));
Output: https://3v4l.org/693sl

Counting values in the same level of a multidemensional array

I'm trying to count how many of the same calendar weeks I have inside the same level of a multidimensional array. My start array can be seen on the picture on the left part, my output is composed of an ID [0] and the rest are the dates corresponding to that ID.
On my code I convert these dates to calendar weeks and then try to count them with a foreach loop and then unset the last values if they are identical to the newest ones, so that I only have the final count. My Problem is that as you can see on the last array [1975]->1->1 the count is not right, it is taking in count also the same weeks from the other ID.
Any kind of help is much appreciated!
My code looks like this:
$array= array();
$arrayCount=array();
$j=0;
foreach ($sorted as $value) {
$k=1;
foreach ($value[1] as $match) {
$time = strtotime($match);
$Calendar_Week = date('W',$time);
$Year = date('Y',$time);
if(!array_key_exists($Calendar_Week , $array)){
$i=1;
$array[$Calendar_Week][$j]=$match;
}
$arrayCount[$sorted[$j][0]][1][0]=$sorted[$j][0];
$arrayCount[$sorted[$j][0]][1][$k][]=$i;
$arrayCount[$sorted[$j][0]][1][$k][]=$Calendar_Week;
$arrayCount[$sorted[$j][0]][1][$k][]=$Year;
// Delete previous counts of the same value
if ($arrayCount[$sorted[$j][0]][1][$k-1][1]==$Calendar_Week & $arrayCount[$sorted[$j][0]][1][$k-1][2]==$Year) {
unset($arrayCount[$sorted[$j][0]][1][$k-1]);
}
$i++;
$k++;
}
$j++;
}
dd($sorted, $arrayCount);
You just need to reset the $i and $array inside the foreach loop
$i=1;
$array = array();
Please check this code
$array= array();
$arrayCount=array();
$j=0;
foreach ($sorted as $value) {
$k=1;
$i=1;
$array = array();
foreach ($value[1] as $match) {
$time = strtotime($match);
$Calendar_Week = date('W',$time);
$Year = date('Y',$time);
if(!array_key_exists($Calendar_Week , $array)){
$i=1;
$array[$Calendar_Week][$j]=$match;
}
$arrayCount[$sorted[$j][0]][1][0]=$sorted[$j][0];
$arrayCount[$sorted[$j][0]][1][$k][]=$i;
$arrayCount[$sorted[$j][0]][1][$k][]=$Calendar_Week;
$arrayCount[$sorted[$j][0]][1][$k][]=$Year;
// Delete previous counts of the same value
if ($arrayCount[$sorted[$j][0]][1][$k-1][1]==$Calendar_Week & $arrayCount[$sorted[$j][0]][1][$k-1][2]==$Year) {
unset($arrayCount[$sorted[$j][0]][1][$k-1]);
}
$i++;
$k++;
}
$j++;
}
dd($sorted, $arrayCount);

Creating a ranked list from multiple arrays

I have 3 arrays that return a url,title,snippet and score from 3 different search engines, the score starts at 100 for the element in the array, the second 99 and so on, I'm trying to combine all 3 into one array. If the urls match from the different arrays I want to add the scores together and then delete the duplicate url. If there is no match between the urls then I just want to put this element into the combined array.
The final combined list should contain all distinct urls with its score,title and snippet, here are my array structures
googleArray
$x=0;
$score=100;
foreach ($js->items as $item)
{
$googleArray[$x]['link'] = ($item->{'link'});
$googleArray[$x]['title'] = ($item->{'title'});
$googleArray[$x]['snippet'] = ($item->{'snippet'});
$googleArray[$x]['score'] = $score--;
$x++;
}
blekkoArray
$score = 100;
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = ($item->{'url'});
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score--; // assign the $score value here
$i++;
}
bingArray
foreach($jsonObj->d->results as $value)
{ $i = 0;
$bingArray[]['Url'] = ($value->{'Url'});
$bingArray[]['Title'] = ($value->{'Title'});
$bingArray[]['Description'] = ($value->{'Description'});
$bingArray[]['score'] = $score--;
$i++;
}
Any help would be great, thanks in advance
This solution depends on a couple of things to work. First, the url and score keys need to be the same, i.e. all lower case and none that are "link." Secondly, the URLs have to be normalized, because they serve as the key for the array. If there are any differences in the URLs, they will show up more than once in the final array.
$merged = array_merge($googleArray, $blekkoArray);
$merged = array_merge($merged, $bingArray);
$combined = array();
foreach ($merged as $key => $value){
$score = (isset($combined[$value['url']]['score'])) ? $value['score'] + $combined[$value['url']]['score'] : $value['score'];
$combined[$value['url']] = $value;
$combined[$value['url']]['score'] = $score;
}
If you don't want to keep the URLs as the key, add this line:
$combined = array_values($combined);
If you want to sort the array by score, you can use usort:
usort($combined, function ($a, $b){
return $b['score'] - $a['score'];
});
print_r($combined);

total value with the same keys within multiple dim array of php

I have an array like this:
$a = array(
array('amount'=>10,'curr'=>'USD'),
array('amount'=>20,'curr'=>'JPY'),
array('amount'=>30,'curr'=>'BAT'),
array('amount'=>50,'curr'=>'BAT'),
array('amount'=>100,'curr'=>'USD')
);
I want to sum all amount the same currency together and return like this:
$total = array('BAT'=>80,
'JPY'=>20,
'USD'=>110
)
$total = array();
foreach($a as $arr){
if(!isset($total[$arr['curr']])){
$total[$arr['curr']] = 0;
}
$total[$arr['curr']] += $arr['amount'];
}

php looping through 2D array

I access the following values like this.
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Low
//next row
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Low
However I need to consolidate this to
$values[0][price]
$values[0][low]
$values[1][price]
$values[1][low]
2 other strange things. The values are strings and I need them to be decimals(2 decimal points) and also the min and the max for price and low accross all the rows
Well the obvious way to build an array of values would be:
$values = array();
for($i = 0; $i < some_maximum_value; $i++) {
$values[$i] = array(
'price' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Price,
'low' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Low,
);
}
TADAAAAAA!!!!
$values = array();
foreach($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $obj){
$values[$key]['price'] = $obj->Price;
$values[$key]['low'] = $obj->low;
}
$myVals = array();
foreach ($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $v)
{
$myVals[$key]['price'] = 1.0 * $c->Price; //hoping string has 2 after the decimal
$myVals[$key]['low'] = 1.0 * $c->Low
}
Try to figure out max/min yourself
Check out foreach loops and string/float conversion
http://us2.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

Categories