Php 对数组值求和
我正在使用drupal开发一个自定义模块,需要对[value]进行汇总, 然而,我尝试了使用array\u column、array\u sum的不同方法,但没有得到解决方案。 任何帮助都将不胜感激。谢谢 代码Php 对数组值求和,php,arrays,drupal,sum,Php,Arrays,Drupal,Sum,我正在使用drupal开发一个自定义模块,需要对[value]进行汇总, 然而,我尝试了使用array\u column、array\u sum的不同方法,但没有得到解决方案。 任何帮助都将不胜感激。谢谢 代码 一对回路和一个累加器是实现这一点的一种方法 $contributionDetails = $node->get('field_contributions')->getValue(); foreach ( $contributionDetails a
一对回路和一个累加器是实现这一点的一种方法
$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;
因此,您有一个包含2个数组的数组,其中包含索引“value”,您只需要使用嵌套的foreach和一个变量
$sum
循环每个数组,该变量对每次迭代的值进行汇总
请尝试以下代码:
$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;
您可以在此处使用数组映射
而不是累加器:
$arraySum=array\u映射(函数($v){
返回重置($v)[“值”];
}美元文本);
打印(数组和($arraySum));//120
编辑,作为完整示例:
$values=[
[['value'=>25]],
[['value'=>75]],
[['value'=>10]],
[['value'=>10]],
];
回波数组和(数组映射)(函数($v){
返回重置($v)[“值”];
},$values));//120
所需的输出是什么?这些值是如何生成的?您是从维护累加器的循环开始的吗?#$contributionDetails=$node->get('field_contributions')->getValue();foreach($contributionDetails as$element){$p=段落::load($element['target\u id']);$text[]=$p->field\u contribution\u percentage->getValue();}
$text返回上述数组@NigelRenDesired输出是[值]
列的总和@可执行的谢谢,的确是120。感谢@ReeceMost优雅的解决方案
$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;
<?php
$sum = 0;
foreach($array as $value) {
foreach ($value as $v){
$sum += $v['value'];
}
}
echo $sum;