如何创建循环函数以根据 php 中的递增索引对数组数据求和

how to create a loop function to sum array data based on increasing index in php

不好意思,我想问一下迭代步骤

我有这样的$数据

array:6 [▼
      0 => 0
      1 => 0.25
      2 => 0.75
      3 => 0.5
      4 => 0.5
      5 => 0.75
]

但我想像下面那样进行迭代或循环 $result

$result[0]=2.75
$result[1]=2.75
$result[2]=2.5
$result[3]=1.75
$result[4]=1.25
$result[5]=0.75

结果说明

$result[0]= 0 + 0.25 + 0.75 + 0.5 + 0.5 + 0.75 = 2.75
$result[1]= 0.25 + 0.75 + 0.5 + 0.5 + 0.75 = 2.75
$result[2]= 0.75 + 0.5 + 0.5 + 0.75 = 2.5
$result[3]= 0.5 + 0.5 + 0.75 = 1.75
$result[4]= 0.5 + 0.75 = 1.25
$result[5]= 0.75 = 0.75

我已经尝试了好几次让这个循环起作用,但它不起作用,这是我最新的代码

    for ($i = 0; $i < count($data); $i++) {
              if (isset($data[$i + 1])) {
                     $result += $data[$i + 1];
             } else {
                 $result += 0;
          }
    }

得到预期结果的正确循环函数是什么,请帮忙,谢谢

使用array_slice() along with foreach()

<?php

$array  = [
      0 => 0,
      1 => 0.25,
      2 => 0.75,
      3 => 0.5,
      4 => 0.5,
      5 => 0.75
];

$finalArray = [];

foreach($array as $key=>$arr){
    $finalArray[] = ($key > 0) ? array_sum(array_slice($array,$key)) : array_sum($array);
}

print_r($finalArray);

https://3v4l.org/LU63i

我建议从数组的末尾循环到数组的开头——使用更长的数组会更快:

$data = [ 0, 0.25, 0.75, 0.5, 0.5, 0.75 ];

$sum = 0;
for ($i = count($data) - 1; $i >= 0; $i--) {
  $sum += $data[$i];
  $data[$i] = $sum;
}

print_r($data);

这并不是要削弱@Anant 的回答,因为它对于短数组来说完全没问题,但是调用 array_sumarray_slice 与仅保持 运行 总和的解决方案相比,每个条目导致以下时间差异:

    10 elements: ~2 times slower
   100 elements: ~5 times slower
  1000 elements: ~85 times slower
 10000 elements: ~750 times slower
100000 elements: ~8800 times slower