douxing6532 2013-05-14 20:19
浏览 69
已采纳

Php Division剩余和阵列

I have an array $blocks It has 4 items with constant values A, B, C, D

$blocks["a"] = 20;
$blocks["b"] = 1000;
$blocks["c"] = 10000;
$blocks["d"] = 50000;

Another function returns a value, lets say 358020 (It's usually high but can drop to a few tens

How would I write a function that will take this value and return an array of how many of each item exists.

Example output something like:

 $output["a"] = 1;
 $output["b"] = 3;
 $output["c"] = 0;
 $output["d"] = 7;

Starting with the largest block, how many of that block fits into the value, then the remainder is passed to the next largest, and so on...

  • 写回答

1条回答 默认 最新

  • duande1146 2013-05-14 21:00
    关注
    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 )
    

    I loop through the credits you have in your system. In this example the credits are order from high to low. When this is not the case you should order them te get the desired result.

    1) For each credit i try to find the max number of times the credit fits within the experience of the particular user. Because floatnumber make no sense we floor() the result of the division.

    2) After i found the number of times the credit fits, I calculate the remainder for the next iteration (next credit). You can find the remainder by calculating the modulus.

    3) Last but not least I cache the number of times the credit fits.

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?