簡體   English   中英

總結數組值

[英]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 ) )
)

我正在 drupal 中處理自定義模塊,需要總結 [value],但是我嘗試了使用 array_column、array_sum 的不同方法,但沒有得到解決方案。 任何幫助,將不勝感激。 謝謝。

代碼

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

幾個循環和一個累加器是實現這一目標的一種方法

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

或者,如果您確定內部數組始終只會出現一次。

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

或者使用您剛剛發布的代碼

$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;

因此,您有一個包含 2 個具有索引“值”的數組的數組,您只需要使用嵌套的 foreach 和一個變量$sum來循環每個數組,該變量對每次迭代的值求和。

試試這個代碼:

<?php 

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

echo $sum;

這將輸出 120

您可以在此處使用array_map而不是累加器:

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

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

編輯,作為一個完整的例子:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM