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'];
}
Related
I'm working with a PHP array that shows a range of prices, where an individual item is in the form of "price from-price to". Here's an example of the array:
Array
(
[0] => $625,000-$700,000
[1] => $550,000-$625,000
[2] => $1,000,000-$1,250,000
[3] => $925,000-$1,000,000
)
I now need to retrieve the lowest and highest price in the array, however as they are a range I first need to pull apart each price in each array item. For example using the above array I would like to be able to return something like this:
$minPrice = 550000;
$maxPrice = 1250000;
I'm new to PHP and completely stumped at this point about how to go about parsing each of the values from each array item then getting the lowest/highest value.
I would put all the normalized prices in an array and use the php max, min functions.
<?php
$ranges = array(
"$625,000-$700,000",
"$550,000-$625,000",
"$1,000,000-$1,250,000",
"$925,000-$1,000,000",
);
$prices = array();
foreach ($ranges as $range) {
$prices = array_merge($prices, explode("-", preg_replace("/[\\$,]/i", "", $range)));
}
$maxPrice = max($prices);
$minPrice = min($prices);
try this:
$array = Array
(
0 => '$625,000-$700,000',
1 => '$550,000-$625,000',
2 => '$1,000,000-$1,250,000',
3 => '$925,000-$1,000,000',
);
$tmp = array();
foreach($array as $key=>$value){
$cleanValue = explode('-', str_replace(array('$',','), array('',''), $value));
foreach($cleanValue as $k=>$v){
$tmp[] = $v;
}
}
$minValue = min($tmp);
$maxValue = max($tmp);
echo $minValue . ' '. $maxValue;
Please refer code below.
First value are exploded to an array and then "$" is removed and then value is converted to integer. Then values are added to array and finally min / max functions are called.
$maxPrice = 0;
$max_curr = 0;
$price_arr = array();
foreach($min_maxs as $min_max){
$min_max_arr = explode("-",$min_max); // string to array
array_walk($min_max_arr,"remove_dollar_commas"); // remove "$"
$price_arr = array_merge($price_arr , $min_max_arr ); // add to final array
}
$maxPrice = max($price_arr); // call max function to get maximum value
$minPrice = min($price_arr); // call min function to get minimum value
function remove_dollar_commas(&$subject){
$subject = intval( str_replace(array("\$",","), "", $subject) );
}
Given the following php array
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
how can I return only the last array per array key 'a'?
Desired result:
$new = array(
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
If I were you, I'd try to store it in a better format that makes retrieving it a bit easier. However, if you are stuck with your format, then try:
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
$tmp = array();
foreach ($a as $value) {
$tmp[$value['a']] = $value;
}
$new = array_values($tmp);
print_r($new);
I would like to know how to get the sum of some key values of multi-dimensional arrays, knowing that some keys are variables; here is an example of the situation :
The array could be written like this :
$array[$dim1][$dim2][$dim3][$dim4] = $variable_value;
$dim1, 2, 3 and 4 are arrays with dimensions, and we don't know the name of the $dim1, 2, 3 and 4.
We want the sum of all $variable_value of each dimensions, but we can't do array_sum($array[$dim1][$dim2][$dim3][$dim4]) because the $dim are not known.
The algorithm I need to find must permit me to apply filters on the sums, like "get the sum of all the $variable_value where $dim3 = $variableX...", so a function like this :
function array_sum_filter($array, $dimension, [$filter_on_key_value])
Any ideas?
use for/foreach loops for looping through the multidimensional array and an if statement to check if $dim3 = $variableX...
You can try this using RecursiveArrayIterator and RecursiveIteratorIterator
$sum = 0;
$specific = 0;
$array = array();
$array["A"]["B"]["C"]["D"] = 5;
$array["A"]["B"]["K"]["D"] = 3;
$array["A"]["C"] = 2;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ( $array_obj as $key => $value ) {
$sum += $value;
if ($key == "D")
$specific += $value;
}
echo $sum, PHP_EOL;
echo $specific, PHP_EOL;
Output
10
8
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.
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