如何在PHP中使用迭代函数运行数学


How to do running math with iterate function in PHP

id想知道如何执行此操作。

假设我有一个值数组[0]123[1] 23242[2] 123123[3] 134234[4] 0[5] 12312[6] 1232[7] 0[8] 2342[9] 0

我怎么能循环通过这个数组,每次它达到零,推到一个新的数组,上一个值的总和直到最后一个0

例如。。。。我的新数组将包含
[0]第一个数组键的总和[0-4][1] [5-7]之和[2] [8-9]之和

我是PHP的新手,不知道该怎么做。比如我如何在查看数组时查看以前的值

如果有人能帮忙,谢谢我很感激

更新:所以乔想让我更新这个,这样他就可以进一步帮助我,所以它在这里…

我想循环遍历和数组,让迭代器计算零之间的和,并将值和一个正在运行的总数存储在一个新数组中。然后我希望能够将它合并回原始数组。。。。例如我该如何使用新数组来计算运行总数。

       Loop array        New Array, with comma delimitted values or maybe a MDA
       [0]5              [0]9,9  (sum of values in loop array between the zeros)
       [1]4              [1]7,16
       [2]0              [2]4,20 
       [3]3              [3]5,25
       [4]2 
       [5]2
       [6]0
       [7]4
       [8]0
       [9]3
       [10]2
       [11]0

最后,最重要的是,我如何将其合并回来,使其看起来像下面的

       [0]5             
       [1]4             
       [2]0,9,9            
       [3]3              
       [4]2 
       [5]2
       [6]0,7,16
       [7]4
       [8]0,4,20
       [9]3
       [10]2
       [11]0,5,25

如果你能帮助我,谢谢你!

$total = 0; // running total
$totals = array(); // saved totals
foreach ($values AS $value) // loop over the values
{
    $total += $value; // add to the running total
    if ($value == 0) // if it's a zero
    {
        $totals[] = $total; // save the total...
        $total = 0; // ...and reset it
    }
}

为了在更新中制作第一个数组,可以这样做:

$total = 0; // running total - this will get zeroed
$grand_total = 0; // running total - this won't be zeroed
$totals = array(); // saved totals
foreach ($values AS $value) // loop over the values
{
    $total += $value; // add to the running total
    $grand_total += $value; // add it to the grand total
    if ($value == 0) // if it's a zero
    {
        $totals[] = $total . ',' . $grand_total; // save the total and the grand_total
        $total = 0; // ...and reset the zeroable total
    }
}

对于您的第二个("终极":p)示例,我们只是将新数组放入bin,而不是保存回我们正在循环的数组中:

$total = 0; // running total - this will get zeroed
$grand_total = 0; // running total - this won't be zeroed
foreach ($values AS $key => $value) // loop over the values - $key here is the index of the current array element
{
    $total += $value; // add to the running total
    $grand_total += $value; // add it to the grand total
    if ($value == 0) // if it's a zero
    {
        $values[$key] = '0,' . $total . ',' . $grand_total; // build the new value for this element
        $total = 0; // ...and reset the zeroable total
    }
}

根本没有经过测试,但我认为它的逻辑应该很好。

这是一个基本的算法任务。。。

$array = array( 1,3,7,9,10,0,5,7,23,3,0,6);
$result = array();
$sum = 0;
for( $i=0,$c=count($array);$i<$c;$i++ ){
    if( $array[$i]==0 ){
        $result[] = $sum;
        $sum = 0;
    }else{
        $sum += $array[$i];
    }
}
print_r($array);