从PHP中的数组中减去一个整数

时间:2014-03-03 01:28:06

标签: php arrays subtraction

我有一个变量:

$sum = 42500;

我有一个如下所示的数组:

$targetsarray = array(
    '5000' => '',
    '5000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '12000' => '',
    '12000' => '',
    '15000' => '',
    '15000' => '',
    '15000' => '',
};

$ targetsarray中的键是从数据库动态生成的,所以它实际上是这样的:

$targetsarray = array(
    $targets => '',
};

我希望在数组中实现的是通过数组中的每个连续键减去$ sum值,以便最终的$ targetsarray看起来像这样:

$sum = 45000;

$targetsarray = array(
    '5000' => '40000', // subtract 5000 from 45000
    '5000' => '35000', // subtract 5000 from 40000
    '10000' => '25000', // subtract 10000 from 35000
    '10000' => '15000', // subtract 10000 from 25000
    '10000' => '5000', // subtract 10000 from 15000
    '10000' => '0', 
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
};

无论如何我可以从$ targetsarray中的每个键中减去$ sum?您将从阵列noobie :)中高度赞赏您的帮助。

1 个答案:

答案 0 :(得分:2)

您可能只有两个数组:

$targetsarray = array(5000, 5000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000);
$anotherarray = array();
$sum = 45000;
foreach($targetsarray as $val){
$anotherarray[] = $sum = ($sum >= $val) ? $sum-$val : 0;
}