PHP如何计算给定的开始和结束年份的年度增长

时间:2015-06-08 07:28:37

标签: php

通过给出2年范围,当前人口和目标人口,如何使用PHP每年获得总人口?

示例:

年|人口

2014 | 100000

2018 | 132000

在纸上计算如下:

132000/100000 = 1.0718

所以我们每年都会得到结果(在纸面上):

2014 = 100000

2015 = 107187(100000 * 1.0718)

2016 = 114890(107187 * 1.0718)

2017 = 123147(114890 * 1.0718)

2018 = 132000

如何保持上一年变量以获得上述结果?

这是我的PHP代码:

for($i > $start; $i < $end; $i++) {
    $this->ProjectPopulation->create(); 
    $increase = array(
        'project_id' => $project_id,
        'year' => $i,
        'percent_increase' => $this->percentage_increase($current_population, $target_population, $year),
        'population' => ??? // Problem here
     );
     $this->ProjectPopulation->save($increase); 
 }

由于

2 个答案:

答案 0 :(得分:1)

有两种资源我建议您查看:

http://php.net/manual/en/ref.math.php

http://www.w3schools.com/php/php_ref_math.asp

你可以通过每次进行计算来解决这个问题,但是使用循环来迭代它们会更快。

这样的事情:

$population = 100000;
$year = 2014;

//I'd print the first one out prior to the loop, or you could put an if($year == 2014) in the loop, your choice really. 

for(i= 0; i < 4; i++)
{
   //do calculation in here.
   echo "The current years is" . $year;  
   $yearsCalculation = $population * 1.0718;  

   //then save that value for the next time around the loop. 
   $population = $yearsCalculation ; 
   echo $yearsCalculation ;      

   //increase years each time round loop
   $year++;
}

如果您想将其存储在MySQL数据库中,您可能需要查看本教程:

http://www.w3schools.com/php/php_mysql_insert.asp

希望有所帮助!

答案 1 :(得分:0)

解决

private function power($current_population, $target_population, $year) {
    $devide = $target_population / $current_population; 
    $pwrdevider = 1 / $year;
    $power = pow($devide, $pwrdevider); 
    return $power;
}

private function percentage_increase($current_population, $target_population, $year) {
    $devide = $target_population / $current_population; 
    $power = pow($devide, 1 / $year);
    $increase = ($power - 1) * 100;
    return $increase;
}

    $start = 2014;
    $end = 2018;
    $diff = $end - $start; 
    for($i = 1, $data = 100000; $i <= $diff; $i++) {  
        $data *= $this->power(100000, 132000, $diff);

        $increase = array(
            'project_id' => 1,
            'year' => $start += 1,
            'percent_increase' => $this->percentage_increase(100000, 132000, $diff),
            'population' => $data 
        );
        print_r($increase); 
    }

这是我的结果

Array
(
   [project_id] => 1
   [year] => 2015
   [percent_increase] => 7.1873373728262
   [population] => 107187.33737283
)
Array
(
   [project_id] => 1
   [year] => 2016
   [percent_increase] => 7.1873373728262
   [population] => 114891.25293076
)
Array
(
   [project_id] => 1
   [year] => 2017
   [percent_increase] => 7.1873373728262
   [population] => 123148.87489076
)
Array
(
   [project_id] => 1
   [year] => 2018
   [percent_increase] => 7.1873373728262
   [population] => 132000
)

全部谢谢