php - 累积数组

标签 php math

我有这个数组:

$a = array(1, 2, 3, 4, 5, 7, 8, 10, 12);

是否有一个函数可以将其转换为:

$b = array(1, 1, 1, 1, 2, 1, 2, 2);

所以基本上:

$b = array ($a[1]-$a[0], $a[2]-$a[1], $a[3]-$a[2], ... ,$a[n]-$a[n-1]);

这是我到目前为止的代码:

$a = $c = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
array_shift($c);
$d = array();
foreach ($a as $key => $value){
   $d[$key] = $c[$key]-$value;
}
array_pop($d);

最佳答案

没有内置函数可以为您执行此操作,但您可以将代码转换为函数。此外,您可以使用常规的 for 循环来循环遍历值,而不是创建第二个数组 $c:

function cumulate($array = array()) {
    // re-index the array for guaranteed-success with the for-loop
    $array = array_values($array);

    $cumulated = array();
    $count = count($array);
    if ($count == 1) {
        // there is only a single element in the array; no need to loop through it
        return $array;
    } else {
        // iterate through each element (starting with the second) and subtract
        // the prior-element's value from the current
        for ($i = 1; $i < $count; $i++) {
            $cumulated[] = $array[$i] - $array[$i - 1];
        }
    }
    return $cumulated;
}

关于php - 累积数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715255/

相关文章:

php - CakePHP 3新实体保存失败,没有错误

php - 我无法使用 SQL 在不同的行中显示我的结果

algorithm - 如何有效地动态计算平均值(移动平均值)?

java - 将数字停在一定范围内

java - 负数的立方根

php - 删除开头的空行

php - 如何在 PHP 中为每个变量值创建互斥方法

algorithm - LUT 与 IEEE-754 32 位浮点的 Newton-Raphson 除法

php - 使用 SQLite3 在 PHP 中创建新数据库

ruby - 将所有项目与同一列表中的另一个项目匹配的算法,其中有些有限制