0
               $buy_amount = 50;                  

                $amount[0] = 100;
                $amount[1] = 150;
                $amount[2] = 50;

                $test;

                $i = $buy_amount;
                $arrlength = count($amount);

                for ($x = 0; $x < $arrlength; $x++) {

                   $test = $amount[$x] - $i;
                    if ($amount[$x] != $test) {
                        $i = $test;
                        echo $test;
                        echo '<br/>';
                    }  
                }

我需要做的是,如果我发送的$buy_amount = 50结果需要像这样减去

例子:

    $amount[0] = 50;
    $amount[1] = 150;
    $amount[2] = 50;

如果我发送$buy_amount = 150结果需要像这样减去

例子:

            $amount[0] = 0;
            $amount[1] = 100;
            $amount[2] = 50;

在这里我需要做的首先从第一个元素中减去并转到其他元素并从中减去,如果buy_amount留下更多则像明智的那样转到其他元素

4

1 回答 1

0

我想这就是你要找的

$amount[0] = 100;
$amount[1] = 150;
$amount[2] = 50;

$buy_amount = 250; // Change to whatever you want

$amount = array_map(
          function ($mValue) use (&$buy_amount)
          {

             if($buy_amount >= $mValue){

                $buy_amount = $buy_amount - $mValue;
                return 0;
             }

             $sReturnValue = $mValue - $buy_amount;
             $buy_amount = 0;

             return $sReturnValue;

          }
          ,$amount);

var_dump($amount);
于 2013-10-30T20:48:54.973 回答