从小数额中减去一大数额

Subtracting one big amount from few smaller

我有一个数组:

array(
key1  => 2,
key2 => 5,
key3 => 10,
keyn => n.
)

我正在尝试从中减去 12 并相应地减少值并更新数组:

key1  => 0 (2 - 12 is -10, so I leave 0)
key2 => 0 (10 left from the first subtraction, so I subtract 10 from the second value, as the result is -5, I leave 0)
key3 => 5 (5 left from the above subtraction so I subtract 5 from 10)
keyn => n (other values not affected by the subtraction should remain unchanged).

我被它困住了。我将不胜感激如何解决问题的任何提示。

试试这个:

$input = array(
    "key1"  => 2,
    "key2" => 5,
    "key3" => 10,
);

$rest = 12;
foreach ($input as $key => $value) {
    $newValue = $value - $rest;
    $rest = 0;
    if ($newValue < 0) {
        $rest = $newValue *= -1;
        $newValue = 0;
    }
    $output[$key] = $newValue;
}

var_dump($output);

输出:

array(3) {
  ["key1"]=>
  int(0)
  ["key2"]=>
  int(0)
  ["key3"]=>
  int(5)
}