我有一个foreach循环,对于每个退休金ID,我都使用对应于该ID的退休金金额,并对30年内的退休金价值应用通货膨胀率。每个人总是会有不同数量的独特养老金。
在foreach循环中,我可以运行它,并让它随着时间的推移产生养老金金额的未来价值,并逐年递增价值。我遇到的问题是,对于每个退休金ID,它都将新的退休金值添加到名称数组中。
例如,如果某人有4个退休金,则在一个数组中产生120个数组值。我想要的是4个(或多少个退休金)数组,每个唯一的退休金值都在其自己的数组中。我的目标是将每个阵列的每个退休金年度加在一起,得出每个人每年的总退休金金额。
例子。
pension 1 array([1] => 100 [2] => 200 [3] => 300…….
pension 2 array([1] => 200 [2]=> 300 [3] => 400……
(然后根据键将每个数组加在一起)
Total pension amount array([1] => 300 [2] => 500 [3] => 700
我一直在尝试各种各样的方法,但是找不到解决方案,我认为foreach可能无法实现这一目标。
回顾一下我需要的解决方案,在每次遍历foreach之后,我需要使用新值创建一个新数组,并且不将它们添加到现有数组中。
任何帮助都将是美好的。
这是我现有的代码。
注意:所有内容都将进入$ pension []
foreach($pen_start as $key => $value){
if($value < $age){
if($pen_cola[$key] == 'Yes'){
$i = 0;
$a = $age;
$previous = $pen_amount[$key];
while($i <= 29 ){
$pension[] = str_replace(',','',number_format(($previous*1.02),2));
$previous = $previous*1.02;
$i++;
$a++;
};
// if yes end
} else if($pen_cola[$key] == 'No' || $pen_cola[$key] == ''){
$i = 0;
$a = $age;
$previous = $pen_amount[$key];
while($i <= 29 ){
$pension[] = str_replace(',','',number_format(($previous),2));
$previous = $previous;
$i++;
$a++;
};
} // if no end
} // if older end
else if($value > $age){
if($pen_cola[$key] == 'Yes'){
$i = 0;
$a = $age;
$previous = 0;
while($i <= 29 ){
if($a < $value){
$amount = 0;
}else if($previous == 0){
$amount = $pen_amount[$key];}
else {$amount = $previous;}
$pension[] = str_replace(',','',number_format(($amount*1.02),2));
$previous = $amount*1.02;
$i++;
$a++;
};
// end if yes
} else if($pen_cola[$key] == 'Yes'){
$i = 0;
$a = $age;
$previous = 0;
while($i <= 29 ){
if($a < $value){
$amount = 0;
}else if($previous == 0){
$amount = $pen_amount[$key];}
else {$amount = $previous;}
$pension[] = str_replace(',','',number_format(($amount),2));
$previous = $amount;
$i++;
$a++;
};
} //end if no
} // if younger end
} // end foreach
在$ pension中使用密钥时,也许您的问题已解决:
$pensions[$key][] = str_replace(',','',number_format(($amount),2));
如果我理解正确,则要执行以下操作:
$result = array(); //or in php 5.5+ []
foreach($pensions as $pension){
foreach($pension as $key => $amount){
if(!isset($result[$key])){
$result[$key] = 0;
}
$result[$key] += $amount;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句