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(); }
Advertisement
Answer
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