How to Sum All Values of a Specific Array Key Recursively

How can I sum all values of a specific array key recursively?

Another alternative:

$sum = 0;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
if($key == 'pv')
$sum += $value;
}
echo $sum;

Update: Just thought I'd mention that this method uses the PHP SPL Iterators.


Salathe Edit:

A simple (relatively) way to filter the keys and to sum the values (without writing a custom Iterator) would be to do some filtering with a RegexIterator, convert the resulting iterator into an array and use the handy array_sum function on it. This is purely an academic exercise and I certainly wouldn't advocate it as the best way to achieve this... however, it is just one line-of-code. :)

$sum = array_sum(
iterator_to_array(
new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
),
'/^pv$/D',
RegexIterator::MATCH,
RegexIterator::USE_KEY
),
false
)
);

Sum of arrays using recursive function

If you are looking for recursion on arrays, you could use RecursiveArrayIterator class , also see RecursiveIteratorIterator class

A simple illustration (taken from this answer):

<?php
$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
$new_arr[] = $v;
}
echo array_sum($new_arr); // "prints" 45

PHP - How to get the sum of a multidimensional array?

You can use array_walk_recursive() in combination with using an outer variable by reference:

$sum = 0;
array_walk_recursive($array, function($number) use (&$sum) {
$sum += $number;
});
echo $sum;

In case an element of an array is an array itself, array_walk_recursive() will iterate through it. Otherwise it will call the function on the element.

How to sum all column values in multi-dimensional array?

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
isset($sumArray[$id]) || $sumArray[$id] = 0;
$sumArray[$id]+=$value;
}
}

print_r($sumArray);

Sum all key/value pairs within a multidimensional PHP array

I try to use a more readable variable name

foreach ($results as $game) {
foreach ($game as $player => $performance) {
if ( !isset($sumArray[$player] ) {
$sumArray[$player] = $performance;
} else {
foreach ( $performance as $type => $value) {
$sumArray[$player][$type] += $value;
}
}
}

Recursion algorithm for the sum of all elements in a list in java

You need to add one parameters to your method: index, to keep track of your current position in the array:

public int sumOfElements(int[] elements, int index) {
if (index >= elements.length)
return 0;
return elements[index] + sumOfElements(elements, index + 1);
}

How to sum of same keys of arrays with their values

I tried this in the following way:

$qty_of_leads_by_levels = array();
$avg_conv_cof_arry = array();
$avg_deal_size = 0;
$total_bgt = 0;

for($i=0;$i<count($arr1);$i++){

foreach($arr1[$i]['qty_of_leads_by_levels'] as $k=>$v){
$qty_of_leads_by_levels[$k] += $v;
}

foreach($arr1[$i]['avg_conv_cof_arry'] as $k1=>$v1){
$avg_conv_cof_arry[$k1] = $avg_conv_cof_arry[$k1] + $v1;
}

$avg_deal_size += $arr1[$i]['avg_deal_size'];
$total_bgt += $arr1[$i]['total_bgt'];
}

General recursive jq for summing all object values found at any level

TL:DR; Over an array of these objects, do . as $dot | reduce ([$dot[] | paths(numbers)] | unique)[] as $path ({}; setpath($path; [$dot[] | getpath($path)] | add))


Since your example input is not valid JSON, here's the JSON I used for testing this. Let me know if this doesn't match with yours:

[
{"a": {"b": 1, "c": 2}, "e": 3},
{"a": { "c": 2, "d": 3}, "f": 4}
]

First, we'll look at how to perform this "additive merge" operation between two objects; afterwards, it should be easy to perform it over an array of objects.

We'll define our function as additive_merge($xs; $ys). First, we'll get a list of all the paths on each of these objects in which there are numbers, with duplicates removed:

([$xs, $ys | paths(numbers)] | unique) as $paths

Then, we'll reduce this list of paths, with an empty object as the initial state, using setpath to set each path in the empty object to the sum of the values of those paths on $xs and $ys:

reduce $paths[] as $path ({}; setpath($path; [$xs, $ys | getpath($path)] | add))

Now, all together, we have our additive_merge function:

def additive_merge($xs;$ys): reduce ([$xs, $ys | paths(numbers)] | unique)[] as $path ({}; setpath($path; [$xs, $ys | getpath($path)] | add));

If we want to run this function over an array, we can either reduce the array over this function:

reduce .[] as $x ({}; additive_merge(.; $x))

Or modify the function so that it works over an array of objects, which is actually really easy; just use the dot input, save it to a variable and decompress it wherever $xs, $ys was used on the previous function:

def additive_merge: . as $dot | reduce ([$dot[] | paths(numbers)] | unique)[] as $path ({}; setpath($path; [$dot[] | getpath($path)] | add));

Hope this helps!



Related Topics



Leave a reply



Submit