我有一个数组:
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)
}