我有一个数组 $块 它有4个具有常数值的项目 A,B,C,D
$blocks["a"] = 20;
$blocks["b"] = 1000;
$blocks["c"] = 10000;
$blocks["d"] = 50000;
另一个函数返回一个值,比方说358020 (它通常很高,但可以降到几十
我如何编写一个函数来获取该值并返回一个数组,其中包含每个项目的数量。
示例输出类似于:
$output["a"] = 1;
$output["b"] = 3;
$output["c"] = 0;
$output["d"] = 7;
从最大的块开始,该块中有多少块符合该值,然后将余数传递给下一个块,依此类推......
答案 0 :(得分:1)
calculateNumberCredits(25000);
function calculateNumberCredits($experience) {
# The credits we have
$credits = array(
'a' => '10000',
'b' => '2000',
'c' => '1000',
);
# Keep track of the amount needed per credit
$timesCreditNeeded = array();
# Start calculating the amount per credit we need
foreach($credits as $creditID => $creditAmount) {
# 1) Calculate the number of times the amount fits within the amount of experience
$times = floor($experience / $creditAmount);
# 2) Calculate the remainder of the above division en cache is for the next calculation
$experience = $experience % $creditAmount;
# 3) Cache the number of times the credit fits within the experience
$timesCreditNeeded[$creditID] = $times;
}
echo '<pre>';
print_r($timesCreditNeeded);
return $timesCreditNeeded;
}
// Will return Array ( [a] => 2 [b] => 2 [c] => 1 )
我遍历你系统中的学分。在这个例子中,信用是从高到低的顺序。如果不是这种情况,您应该订购它们以获得所需的结果。
1)对于每个赠送金额,我会尝试查找赠送金额符合特定用户体验的最大次数。因为floatnumber毫无意义,所以我们将()分区的结果放在一边。
2)在我找到信用证适合的次数后,我计算下一次迭代的余数(下一次信用)。您可以通过计算modulus找到余数。
3)最后但并非最不重要的是,我会缓存信用证适合的次数。
希望这有帮助!