如何从数组中获取最大值后总结所有剩余金额?

时间:2021-08-24 22:56:50

I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

我对这个问题犹豫不决,不管是否应该问。我认为这是一个更合乎逻辑的问题。但是,我无法弄明白。

I have a array that may include

我有一个可能包含的数组

$programFees = [100,200,100,500,800,800]

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

我可以使用max($ programFees)从这个数组中获取最大值。如果我有2个最大值,如800,800,我只想拿一个。我意识到php max可以解决这个问题。

But, I want to sum up all remaining amount from that array.

但是,我想总结一下该阵列的所有余额。

e.g

$maxProgramFees = max($programFees); 
//I got 800 and remaining amount is [100,200,100,500,800]

My total amount should be 1700. Which approach should I use to get this amount?

我的总金额应该是1700.我应该使用哪种方法来获得这笔金额?

2 个解决方案

#1


5  

Sort the array, grab the largest, then shift the array to get the remainder values. Add those values

对数组进行排序,获取最大值,然后移动数组以获取余数值。添加这些值

<?php 
$programFees = [100, 200, 100, 500, 800, 800];
rsort($programFees); //sort high -> low

$highest = $programFees[0]; // 800
array_shift($programFees); // remove the highest value

$sum = array_sum($programFees); // 1700

rsort() documentation

array_shift() documentation

array_sum() documentation

#2


1  

@helllomatt has already provided a very good answer, however, if you cannot modify the array order for some reason you may want to try something like this.

@helllomatt已经提供了一个非常好的答案,但是,如果由于某种原因你不能修改数组顺序,你可能想尝试这样的事情。

$programFees = [100,200,100,500,800,800];
$maxProgramFees = max($programFees);
$sum = array_sum(array_diff($programFees, array($maxProgramFees)));

I would assume the rsort() answer would be the faster option.

我认为rsort()答案是更快的选择。

#1


5  

Sort the array, grab the largest, then shift the array to get the remainder values. Add those values

对数组进行排序,获取最大值,然后移动数组以获取余数值。添加这些值

<?php 
$programFees = [100, 200, 100, 500, 800, 800];
rsort($programFees); //sort high -> low

$highest = $programFees[0]; // 800
array_shift($programFees); // remove the highest value

$sum = array_sum($programFees); // 1700

rsort() documentation

array_shift() documentation

array_sum() documentation

#2


1  

@helllomatt has already provided a very good answer, however, if you cannot modify the array order for some reason you may want to try something like this.

@helllomatt已经提供了一个非常好的答案,但是,如果由于某种原因你不能修改数组顺序,你可能想尝试这样的事情。

$programFees = [100,200,100,500,800,800];
$maxProgramFees = max($programFees);
$sum = array_sum(array_diff($programFees, array($maxProgramFees)));

I would assume the rsort() answer would be the faster option.

我认为rsort()答案是更快的选择。