简体   繁体   English

如何在重复字段中仅求和PHP中foreach循环的单个值?

[英]How to SUM only a single value of a foreach loop in PHP in repetitive fields?

I have this loop 我有这个循环

foreach($sudentname as $key => $v){ 
    echo 'Student Name : '.$v.'<br/>';
    echo 'Admission Number : '.$admissionnmbr[$key].'<br/>';
    echo 'Payment Type : '.$purpose[$key].'<br/>';
    echo 'Amount : '.$amount[$key].'<br/>';
    echo 'Grade : '.$grade[$key].'<br/>';
}

I am using this to get values from some repetitive fields. 我正在使用它来获取一些重复字段的值。

I have to SUM of the amounts to get the total of it. 我必须对金额进行求和才能得出总额。

Let say someone is repeating the repetitive section for three times. 假设某人重复了重复部分三遍。 Then the amount will be there 3 times with three different values. 然后,该数量将出现3次,并带有三个不同的值。 ex: 10, 20, 30 例如:10、20、30

To calculate the total I want to SUM that value.. and display that out side of the loop. 要计算总数,我想求和该值..并将其显示在循环之外。

How can do that? 那怎么办

If I want to SUM the whole array I can do that using array_sum 如果我想array_sum整个数组,可以使用array_sum

You need to couple it with array_map() to select the f_count column first: 您需要将其与array_map()耦合以首先选择f_count列:

array_sum(array_map(function($item) { 
    return $item['yourkey']; 
}, $arr));

Of course, internally, this performs a double loop; 当然,在内部,这会执行一个双循环。 it's just that you don't see it inside the code. 只是您在代码中看不到它。 You could use array_reduce() to get rid of one loop: 您可以使用array_reduce()摆脱一个循环:

array_reduce($arr, function(&$res, $item) {
    return $res + $item['yourkey'];
}, 0);

However, if speed is the only interest, foreach remains the fastest: 但是,如果速度是唯一的兴趣,那么foreach仍然是最快的:

$sum = 0;
foreach ($arr as $item) {
    $sum += $item['yourkey'];
}

This is thanks to the "locality" of the variables that you're using, ie there are no function calls used to calculate the final sum. 这要归功于您使用的变量的“局部性”,即,没有用于计算最终总和的函数调用。

Try this 尝试这个

   <?php 
$totalAmount=0;
    foreach($sudentname as $key => $v){ 
        $totalAmount +=$amount[$key]; // to sum all of amount
        echo 'Student Name : '.$v.'<br/>';
        echo 'Admission Number : '.$admissionnmbr[$key].'<br/>';
        echo 'Payment Type : '.$purpose[$key].'<br/>';
        echo 'Amount : '.$amount[$key].'<br/>';
        echo 'Grade : '.$grade[$key].'<br/>';
    }
    echo $totalAmount;
?>
$Result = 0;
foreach($sudentname as $key => $v){ 
    echo 'Student Name : '.$v.'<br/>';
    echo 'Admission Number : '.$admissionnmbr[$key].'<br/>';
    echo 'Payment Type : '.$purpose[$key].'<br/>';
    echo 'Amount : '.$amount[$key].'<br/>';
    $Result += $amount[$key]; // increment $Result with the $amount[$key]
    echo 'Grade : '.$grade[$key].'<br/>';
}
echo "Result: $Result";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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