How to get SUM value in a array? - php

I have 2 elements which has the value of member which is 5
I want to get the sum of all value of member
[member] => 5 + [member] => 5 = 10
The output should be 10
This is my array
Array
(
[0] => Array
(
[membUid] => 0090000816
[service_id] => 0
[member] => 5
)
[1] => Array
(
[membUid] => 0090000867
[service_id] => 0
[member] => 5
)
)
This is my code:
foreach($result['content'] as $res){
sum($res['member']);
}

Does this work?
$sum = 0;
foreach ($result as $res) {
$sum += $res['member'];
}
echo $sum;

alternative solution, with array_sum & array_map functions
echo array_sum(array_map(function($i){return $i["member"];},$result['content']));

Related

Keep only the three highest values in array of array in php

I have an array of 83 arrays (an array that I have a chunk in 83). I'm trying to keep only the three highest values of each array. All the numbers in each array are included between -1 and 1. There is necessarily a 1 in each array that I don't want to count in my three highest values.
Array
(
[0] => Array
(
[1] => 0.5278533158407
[2] => 0.4080014506744
[3] => 0.5086879008467
[5] => 0.3950042642736
[6] => 1
[1] => Array
(
[1] => 1
[2] => 0.52873390443395
[3] => 0.52518076782133
[4] => 0.52983621494599
[5] => 0.54392829322042
[6] => 0.53636363636364
Etc...
I'm trying the below code but it doesn't work.
for ($i = 0; $i < sizeof($list_chunk); $i++) {
arsort($list_chunk[$i]);
}
for ($i = 0; $i < sizeof($list_chunk); $i++) {
array_slice($list_chunk[$i],1,3,true);
}
print("<pre>");
print_r($list_chunk);
print("</pre>");
Someone could help me? Thanks a lot
This solution uses a foreach loop with a reference to the subarray. The subarray is sorted in descending order of size. The first to third elements are extracted. If the first element is 1, then 3 elements are extracted from the 2 element onwards.
foreach($array as &$arr){
rsort($arr);
$start = $arr[0] == 1 ? 1 : 0;
$arr = array_slice($arr,$start,3);
}
Result:
array (
0 =>
array (
0 => 0.5278533158407,
1 => 0.5086879008467,
2 => 0.4080014506744,
),
1 =>
array (
0 => 0.54392829322042,
1 => 0.53636363636364,
2 => 0.52983621494599,
),
)
Full sample to try: https://3v4l.org/pUhic

merge/sum multi dimentional array php

I'm trying to merge/sums 2 arrays that can contain integers or more arrays (themselves containing integer).
When the values are integers, I need to sum them in the final array.
When the values are arrays, I need to loop through the values and sum them in the final array.
If a value or a sub-array exists only in 1 of the base array, it needs to be added in the sub-array of the final array. (This is what I can't do)..)
My arrays are like this:
ARRAY 1
[1466859600] => Array
(
[TOTAL] => 27217
[AAA] => Array
(
[FD_CDP] => 1746
[LO_SC_MIC] => 4654
[FD_ATS] => 893
[CDP] => 40
[SUPERVISION] => 9
[CONTROL] => 4
[ATS] => 4
[EVT_ACK] => 3
)
[BBB] => Array
(
[FD_CDP] => 1376
[LO_SC_MIC] => 4606
[FD_ATS] => 826
[FD_ATSS] => 451
[LO_SFRC] => 4
[FD_S2] => 259
[2_LOSC] => 2
)
[CCC] => Array
(
[FD_CDP] => 1333
[LO_SC_MIC] => 4725
[FD_ATS] => 856
[CONTROL] => 4
[ATS] => 2
[EVT_ACK] => 5
)
ARRAY 2
[1466859600] => Array
(
[TOTAL] => 95406
[AAA] => Array
(
[FD_ATSS] => 1719
[LO_SC_MIC] => 16830
[CONTROL] => 16
[NEW] => 7
[NOEL] => 206
)
[BBB] => Array
(
[SUPERVISION] => 23
[CDP] => 158
[CONTROL] => 40
[2_LOSC] => 14
[ATS] => 6
[EVT_ACK] => 4
)
[CCC] => Array
(
[EVT_ACK] => 167
[LO_SFRC] => 248
[SUPERVISION] => 23
)
I wrote a function like this :
function sumArrayValues($array1, $array2)
{
foreach ($array1 as $key => $value)
{
if (is_array($array1[$key]))
{
echo "it's an array\n I need to reloop\n";
sumArrayValues($array1[$key], $array2[$key]);
}
else
{
echo "FIRST VALUE TO SUM\n";
print_r($array1[$key]."\n");
echo "SECOND VALUE TO SUM\n";
print_r($array2[$key]."\n");
$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
echo "--------RESULT of SUM array1&2----------\n";
}
}
return $array1;
}
But this function doesn't take into account 2 (and probably more) cases: if the sub-array are not in the same order, if a sub-array or a value only exist in second array.
A example of function would be a good help, but on a more fundamental level, I even can't figure the algorithm to do that.
Any ideas ?
You can get all the keys for the foreach loop, live demo.
Note, you also can check if a key of any array is undefined, then save the defined value for the key.
function sumArrayValues($array1, $array2)
{
$keys = array_keys($array1 + $array2);
foreach ($keys as $key)
{
if (is_array($array1[$key]) || is_array($array2[$key]))
$array1[$key] = sumArrayValues($array1[$key], $array2[$key]);
else
#$array1[$key] = (int)$array1[$key] +(int)$array2[$key];
}
return $array1;
}

Multiple array data in php and get the SUM

I am using Codeigniter and I have a function like this .
function total_income(){
$data['total_income'] = $this->mod_products->total_income();
echo"<pre>";
print_r($data['total_income']);
}
The above code return an array like this.
Array
(
[0] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[1] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[2] => stdClass Object
(
[sub_product_price] => 50
[quantity] => 15
)
[3] => stdClass Object
(
[sub_product_price] => 500
[quantity] => 5
)
)
Now I want to get the [sub_product_price] and multiply that value with [quantity] .Then I want to get the array_sum. I don't have an idea how to do that. Could some one help me It would be grate ,
Cheers!! Rob
$sum = 0;
foreach ($array as $obj) {
$sum += ($obj->quantity * $obj->sub_product_price);
}
Add the all values after multiplication in an empty array and use array_sum() to get the final value.
$temp = array();
foreach($data['total_income'] as $in)
{
$temp[] = $in->sub_product_price * $in->quantity;
}
$total = array_sum($temp);
Explanation:
array_sum() returns the sum of all the values of an array.
Example,
$array = array(4,5,6);
echo array_sum($array); // 15

Sum Multi Dimensional array if the sub key is exists

I have this array which has more then 100 results but some of these has same sub array key. I would like to sum array element which has same key which is [/xyx/888350] in this example. However, I want to keep the format as it is which is two dimensional.
Array
(
[0] => Array
(
[/xyx/888350] => /xyx/888350
[visitors] => 1
[pageviews] => 2
[uniquepageviews] => 1
)
[1] => Array
(
[/xyx/888350] => /xyx/888350
[visitors] => 1
[pageviews] => 3
[uniquepageviews] => 1
)
[2] => Array
(
[/xyx/888350] => /xyx/888350
[visitors] => 1
[pageviews] => 2
[uniquepageviews] => 1
)
[3] => Array
(
[/xyx/102254] => /xyx/102254
[visitors] => 1
[pageviews] => 2
[uniquepageviews] => 1
)
)
I am expecting out put something like below:
Array
(
[0] => Array
(
[/xyx/888350] => /xyx/888350
[visitors] => 2
[pageviews] => 7
[uniquepageviews] => 2
)
[1] => Array
(
[/xyx/102254] => /xyx/102254
[visitors] => 1
[pageviews] => 3
[uniquepageviews] => 1
)
)
Thanks in advance.
Loop the array, and store the results in a temporary array, by using the first value as a key:
$input = /*your example data here*/;
$result = array();
foreach($input as $data){
$keys = array_keys($data);
$key = $keys[0]; //get the first key of the array a.k.a '/xyx/888350'
if(isset($result[$key])){
//sum the values if we have this key
$result[$key]['visitors'] += $data['visitors'];
$result[$key]['pageviews'] += $data['pageviews'];
$result[$key]['uniquepageviews'] += $data['uniquepageviews'];
}else{
$result[$key] = $data;
}
}
//drop the extra keys and return a indexed array with the summed values
return array_values($result);
$results=$service->data_ga->get("");
$stats = array();
for ($i=0; $i < count($stats_results=$results->getRows()) ; $i++)
{
$stats[]=array(
'path'=>$stats_results[$i][1],
'visitors'=>$stats[$i]['visitors'] + $stats_results[$i][2],
'pageviews'=>$stats[$i]['visitors'] + $stats_results[$i][3],
'uniquepageviews'=>$stats[$i]['visitors'] + $stats_results[$i][4]
);
}
$result = array();
foreach($stats as $data){
$keys = array_keys($data);
$key = $keys[0]; //get the first key of the array a.k.a '/xyx/888350'
if(isset($result[$key]))
{
//sum the values if we have this key
$result[$key]['visitors'] += $data['visitors'];
$result[$key]['pageviews'] += $data['pageviews'];
$result[$key]['uniquepageviews'] += $data['uniquepageviews'];
}else{
$result[$key] = $data;
}
}
echo "<pre>";
print_r($result);
Output:
Array
(
[path] => Array
(
[path] => /path/888350
[visitors] => 3
[pageviews] => 7
[uniquepageviews] => 3
)
)
Thanks both of you. As time goes on I will also answer questions other people have. I have just started my career. Thank you guys :)

Counting unique arrays inside the array in PHP?

I have some array containing other arrays:
Array
(
[0] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[1] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[2] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 24
[madeDatetime:protected] => 2011-04-18 11:31:26
[stake:protected] => 13.00
[status:protected] => 6
)
)
What's the best way of counting unique arrays?
Off the top of my head you could try:
$hashes = array();
$uniques = 0;
foreach($array as $slip) {
$hash = sha1(serialize($slip));
if(!in_array($hash, $hashes)) {
++$uniques;
$hashes[] = $hash;
}
}
var_dump($uniques); // prints total number of unique objects.
Edit:
#biakaveron's idea looks better though and could be adapted to:
$uniques = count(array_unique($array, SORT_REGULAR));
var_dump($uniques); // prints total number of unique objects.
This previous question has various solutions for removing duplicate arrays from within an array. If you implement any of them and then use sizeof() on the returned array you will have your solution.
eg:
<?php
$yourarray = array();
$tmp = array ();
foreach ($yourarray as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
echo sizeof($tmp);
?>

Categories