Sum Multi Dimensional array if the sub key is exists - php

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

Related

Combining Arrays while merging the values with the same key

I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);

Combine values by key in single array

Nothing really does exactly what I want to achieve. I have the following array:
Array(
[0] => Array
(
[chicken] => 7
)
[1] => Array
(
[cheese] => 9
)
[2] => Array
(
[marinade] => 3
)
[3] => Array
(
[cookbook] => 7
)
[4] => Array
(
[chicken] => 11
)
[5] => Array
(
[cheese] => 6
)
[6] => Array
(
[marinade] => 12
)
)
I want to sum all values by their key. If the key is multiple times in the array, like chicken, I want to sum the values.
array
(
[chicken] => 18,
[cheese] => 16
... etc
)
So you'd first need a loop to iterate through the first array to get the second-level arrays. Then you can get the current key and value from each of those arrays, summing the values in a new array associated by the key.
// where the sums will live
$sum = [];
foreach($array as $item) {
$key = key($item);
$value = current($item);
if (!array_key_exists($key, $sum)) {
// define the initial sum of $key as 0
$sum[$key] = 0;
}
// add value to the sum of $key
$sum[$key] += $value;
}
Here simple example i hope it's help you.
$result = array();
foreach($data as $key => $value)
{
$valueKey = key($value);
$result[$valueKey] += $value[$valueKey];
}

Average result of multidimensional array in PHP

This is a question for all the array specialists out there. I have an multi dimension array with a result as number (can be 0,1 or 2) and need the average for each grouped by parent.
In the example below the calculation would be:
subentry1_sub1 = 2 + 2 = 4 (4/2=2)
subentry1_sub2 = 1 + 1 = 2 (2/2=1)
So what I try to archive in PHP is the following result:
subentry1_sub1 average = 2
subentry1_sub2 average = 1
...
I already tried some solutions from similar questions. But with all the recursive functions I didn't managed to get it aggregated by the last child name (e.g. subentry1_sub1).
Any ideas?
EDIT:
subentry1_sub1 is 2 + 2 because its two times in the array
[entry1] => [subentry1] => [subentry1_sub1] => result
[entry2] => [subentry1] => [subentry1_sub1] => result
Array
(
[entry1] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
[entry2] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
)
Try this code. In this i have created a new array $sum which will add result value of same subentry childs with same key and another array $count which will count the number of times each key repeats
<?php
$data = array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
)
);
$sum = array();
$repeat = array();
foreach($data as $input){
foreach($input as $array){
foreach($array as $key=>$value){
if(array_key_exists($key,$sum)){
$repeat[$key] = $repeat[$key]+1;
$sum[$key] = $sum[$key] + $value['result'];
}else{
$repeat[$key] = 1;
$sum[$key] = $value['result'];
}}}}
echo "<pre>";
print_r($sum);
print_r($repeat);
foreach($sum as $key=>$value){
echo $key. ' Average = '. $value/$repeat[$key]."</br>";
}
Output
Array
(
[subentry1_sub1] => 4
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
Array
(
[subentry1_sub1] => 2
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
subentry1_sub1 Average = 2
subentry1_sub2 Average = 1
subentry2_sub1 Average = 1
subentry2_sub2 Average = 1
You can easily calculate avg now
Note : As you mentioned you are counting occurence of subentry1_sub1 etc so i did the same so it will also count whether key result exists or not
I know this is an old thread but im pretty sure there is a much easier way of doing this for anyone who is interested:
If you know the result will always be a number:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_column($sub_data, 'result');
$averages[$entry_name][$sub_name] = array_sum($sub_results)/count($sub_results);
}
}
If its possible the result could be NULL or empty, this will check it and return 'N/A' if there is no valid data to calculate an average from:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_filter(array_column($sub_data, 'result'));
$averages[$entry_name][$sub_name] = (count($sub_results) > 0 ? array_sum($sub_results)/count($sub_results) : 'N/A');
}
}
both of these solutions will give you an averages array that will output the average per subentry per entry.
Try this like,
<?php
$data=array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>3),
'subentry1_sub2'=>array('value'=>'abc','result'=>3)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>2),
'subentry2_sub2'=>array('value'=>'abc','result'=>8)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>6),
'subentry1_sub2'=>array('value'=>'abc','result'=>6)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>10),
'subentry2_sub2'=>array('value'=>'abc','result'=>12)
)
)
);
foreach($data as $k=>$v){
echo "----------------$k---------------------\n";
if(is_array($v)){
foreach($v as $a=>$b){
if(is_array($b)){
echo $a.' average = ';
$c=array_keys($b);// now get *_sub*
$v1=isset($b[$c[0]]['result']) ? $b[$c[0]]['result'] : '';
$v2=isset($b[$c[1]]['result']) ? $b[$c[1]]['result'] : '';
echo ($v1+$v2)/2;
echo "\n";
}
}
}
}
Online Demo
In the meantime I found a simple working solution myself:
foreach ($data as $level2) {
foreach ($level2 as $level3) {
foreach ($level3 as $keyp => $level4) {
foreach ($level4 as $key => $value) {
if($key == 'result') $stats[$keyp] += $value;
}
}
}
}
With that you get the total for every key in an new array $stats.
But be sure to checkout the solution from user1234, too. It's working great and already includes the calculation of the average.
https://stackoverflow.com/a/39292593/2466703

How to merge values in foreach loop php

I am working in multidimensional array, i have an array like this and i want to merge array
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19
[productId] => 50
)
[1] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 20
[productId] => 50
)
All i need is to make array by join orderId 19,20
ie,
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 50
)
I want to arrange like this.please help me to achieve this
You can try something like this
//This is your old array that you describe in your first code sample
$old_array = array();
// This will be the new joined array
$new = array();
// This will hold the key-pairs for each array within your initial array
$temp = array();
// This will hold all the values of orderId
$orderId = array();
// Loop through each first-level array with the original array
foreach($old_array as $val) {
//Loop through each second-level array
foreach($val as $key => $value) {
// Set the key-pair values in the $temp array
$temp[$key] = $temp[$value];
if($key == "orderId") {
// Add the current orderId value to the orderId array
array_push($orderId,$value);
// Join all the orderId values into the $temp array
$temp[$key] = join(",", $orderId);
}
}
}
//Push the final values to the new array to get a 2 dimensional array
array_push($new, $temp);
Note: I did not test any of the following code so it is very likely to not work at first.
This is also VERY bad array design and there are more likely easier and more practical solutions to this problem, but you will need to give more details on what you want to achieve
$original_array = array(); //this is the array you presented
$new_array = array(); //this is the output array
foreach($original_array as $arr) {
foreach($arr as $key => $value) {
if(array_key_exists($key, $new_array)) { //if you already assigned this key, just concat
$new_array[0][$key] .= "," . $value;
} else { //otherwise assign it to the new array
$new_array[0][$key] = $value;
}
}
}
It will give you the desired result
$arrNew = array();
$i = 0;
foreach($multiDArray as $array)
{
foreach($array as $key=>$value)
{
if($i > 0)
{
if($arrNew[$key] != $value)
{
$str = $arrNew[$key].','.$value;
$arrNew[$key] = $str;
}
}
else
{
$arrNew[$key] = $value;
}
}
$i++;
}
print_r($arrNew);
Result:
Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 1
)

php array_combine function is not working properly?

This is my code
$pro_qty = '';
$se_pro = '';
$pro_id_nn = $this->getDataAll("SELECT session_pro_id,session_pro_qty FROM `jp_session` WHERE session_pro_id IN (".$pro_id.") AND order_status='3'");
foreach($pro_id_nn as $pro)
{
$pro_qty[] = $pro['session_pro_qty'];
$se_pro[] = $pro['session_pro_id'];
}
$proqty = array_combine($pro_qty,$se_pro);
echo '<br>';
print_r($se_pro);
echo '<br>';
print_r($pro_qty);
echo '<br>';
print_r($proqty);
OUTOUT
first array
$se_pro = Array ( [0] => 5 [1] => 1 [2] => 1 ) ;
second array
$pro_qty = Array ( [0] => 24 [1] => 24 [2] => 22 ) ;
Finally combine two array result is
$proqty = Array ( [5] => 24 [1] => 22 );
but my expecting result is
$proqty = Array ( [5] => 24 [1] => 24 [1] => 22 );
how can i get my expecting result . thanks in advance.
Your expected result is not possible, you cannot map one key (1) to two different values (24 and 22). Perhaps you should look at a different solution, such as a "jp_session" class which contains the two values, and then just store it in a list.
simple solution
foreach($pro_id_nn as $pro)
{
$pro_qty[$pro['session_pro_id']][] = $pro['session_pro_qty'];
}
Try this one
<?php
$se_pro = Array ( 0 => 5, 1 => 1, 2 => 1 ) ;
$pro_qty = Array ( 0 => 24, 1 => 24, 2 => 22 ) ;
$a=sizeof($se_pro);
for($i=0;$i<$a;$i++)
{
$b=$se_pro[$i];
$c=$pro_qty[$i];
$temp[$b]=$c;
$i++;
}
print_r($temp);
?>
But one condition '$se_pro' values not repeat and both array are same size
in array_combine() If two keys are the same, the second one prevails..
you can get the result like -
Array
(
[24] => Array
(
[0] => 5
[1] => 1
)
[22] => 3
)
the other way can be
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
$output = array();
$size = sizeof($keys);
for ( $i = 0; $i < $size; $i++ ) {
if ( !isset($output[$keys[$i]]) ) {
$output[$keys[$i]] = array();
}
$output[$keys[$i]][] = $values[$i];
}
this will give the output like -
Array ( [24] => Array ( [0] => 5 [1] => 1 ) [22] => Array ( [0] => 1 ) )
or you can use
<?php
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $keys, $values);
print_r($arrResult);
?>
depending upon which output is more suitable for you to work with.

Categories