Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 百分比差循环数组_Php_Laravel_Laravel 4 - Fatal编程技术网

Php 百分比差循环数组

Php 百分比差循环数组,php,laravel,laravel-4,Php,Laravel,Laravel 4,第一次贴海报,所以我希望你们能帮我做一件我认为很简单但还没弄明白的事情 我有一个名为exports的表,其中有一个年份和值字段。我目前有1992年至2011年的数据 我希望能够从数据库中提取这些数据,然后计算同比百分比差异,并将结果存储在数组中,以便将数据传递到视图文件 例如:((1993-1992)/1992)*100)然后((1994-1993)/1993)*100)然后((1995-1994)/1994)*100)等等 我需要它是灵活的,这样我可以添加未来的数据。例如,我最终将添加2012

第一次贴海报,所以我希望你们能帮我做一件我认为很简单但还没弄明白的事情

我有一个名为exports的表,其中有一个年份和值字段。我目前有1992年至2011年的数据

我希望能够从数据库中提取这些数据,然后计算同比百分比差异,并将结果存储在数组中,以便将数据传递到视图文件

例如:((1993-1992)/1992)*100)然后((1994-1993)/1993)*100)然后((1995-1994)/1994)*100)等等

我需要它是灵活的,这样我可以添加未来的数据。例如,我最终将添加2012年的数据


我真的被困在如何推进这一点上了。非常感谢您的帮助。

如果我理解正确,解决方案就不必那么复杂了。一个简单的SELECT查询,用于获取年份和值,然后可以使用PHP中的循环进行查询并计算百分比。大概是这样的:

<?php
// Get all the data from the database.
$sql = "SELECT year, value FROM exports";
$stmt = $pdo->query($sql);

// An array to store the precentages.
$percentages = [];

// A variable to keep the value for the last year, to be
// used to calculate the percentage for the current year.
$lastValue = null;

foreach ($stmt as $row) {
    // If there is no last value, the current year is the first one.
    if ($lastValue == null) {
        // The first year would always be 100%
        $percentages[$row["year"]] = 1.0;
    }
    else {
        // Store the percentage for the current year, based on the last year.
        $percentages[$row["year"]] = (float)$row["value"] / $lastValue;
    }

    // Overwrite the last year value with the current year value
    // to prepare for the next year.
    $lastValue = (float)$row["value"];
}
array (
    [1992] = 1.0,
    [1993] = 1.2,
    [1994] = 0.95
    ... etc ...
)

我们想先看看你的代码,请展示你的尝试,谢谢你的帮助。我成功地用你的逻辑实现了我的目标。