从几个较小的数量中减去一个大的数量

问题描述

我有一个数组:

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)
}