简体   繁体   中英

Sum up the array values

Array
(
    [0] => Array( [0] => Array( [value] => 25 ) )
    [1] => Array( [0] => Array( [value] => 75 ) )
    [2] => Array( [0] => Array( [value] => 10 ) )
    [3] => Array( [0] => Array( [value] => 10 ) )
)

I am working on a custom module in drupal and need to sum up the [value], However I tried different approaches using array_column, array_sum, but didn't get the solution. Any help would be appreciated. Thanks.

Code

$contributionDetails = $node->get('field_contributions')->getValue();              
foreach ( $contributionDetails as $element ) {
    $p = Paragraph::load( $element['target_id'] );
    $text[] = $p->field_contribution_percentage->getValue();             
}

A couple of loops and an accumulator is one way to achieve this

$tot = 0;
foreach ($array as $a){
    foreach ($a as $b){
        $tot += $b['value'];
    }
}
echo $tot;

Or if you are sure there will always only be one occurance of the inner array.

$tot = 0;
foreach ($array as $a){
    $tot += $a[0]['value'];
}
echo $tot;

Or using the code you just posted

$contributionDetails = $node->get('field_contributions')->getValue();              
$tot = 0;
foreach ( $contributionDetails as $element ) {
    $p = Paragraph::load( $element['target_id'] );
    $text[] = $p->field_contribution_percentage->getValue();
    $tot += $p->field_contribution_percentage->getValue();
}
echo $tot;

So you have an array containing 2 arrays which have the index 'value', you just need to loop each array using nested foreach and a variable $sum which sum up the value on each iteration.

Try this code:

<?php 

$sum = 0;
foreach($array as $value) {
    foreach ($value as $v){
        $sum += $v['value'];
    }
}

echo $sum;

This will output 120

You could make use of array_map here instead of an accumulator:

$arraySum = array_map(function ($v) {
  return reset($v)['value'];
}, $text);

print_r(array_sum($arraySum)); // 120

Edit , as a full example:

$values = [
    [['value' => 25]],
    [['value' => 75]],
    [['value' => 10]],
    [['value' => 10]],
];

echo array_sum(array_map(function ($v) {
  return reset($v)['value'];
}, $values)); // 120

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM