如何在PHP中使用iterate函数运行数学运算

Kyl*_*lie 0 php arrays math loops

我想知道如何执行此操作.

说我有一组数值[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]的总和[8] [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
Run Code Online (Sandbox Code Playgroud)

最后,最重要的是,如何将其合并,以便它看起来如下所示

       [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
Run Code Online (Sandbox Code Playgroud)

谢谢你能帮助我!

Joe*_*Joe 6

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

要在更新中创建第一个数组,请执行以下操作:

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

对于你的第二个("终极":P)例子,我们只是将新数组加入,然后保存回我们循环的数组中:

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

根本没有测试,但我认为它的逻辑应该是相当的.