我有一个预测循环,对于每个养老金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之后,我需要创建一个具有新值的新数组,而不是让它们添加到现有数组中。
任何帮助都会很好。
这是我现有的代码。
注意:所有东西都进入$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发布于 2015-07-24 04:53:30
也许当您使用$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;
}
}https://stackoverflow.com/questions/31601932
复制相似问题