陷入phpforeach循环-需要再次使用相同的键运行循环


Stuck with php foreach loop - need to run the loop with the same key once more

好吧,我被这个卡住了。我有一个嵌套在另一个foreach循环中的foreach循环。现在,在某些条件下,我需要使用相同的键再次运行外循环。虽然有这个函数prev($array),它会将迭代器设置到以前的位置,但这似乎不起作用,php文档说

由于foreach依赖于>内部数组指针,在循环中更改它可能会导致意外行为。

我正在处理的数组是一个关联数组,所以显然我无法轻松切换到整数索引迭代。

    $arrLocalCopy = $this->arrPrintOut;
    $groupCounter = 0; 
    foreach($this->arrPrintOut as $kOne => $rowA){
        //first and last row contain titles and totals, so we skip them
        if($groupCounter < 1 || $groupCounter == sizeof($this->arrPrintOut)-1  ){ $groupCounter++; continue; }
        $rowCounter = 0;
        foreach($arrLocalCopy as $k => $rowB){
            //skip rows that are "before" the outer loops row, as we want to compare only rows below the row we compare to.
            if ($rowCounter <= $groupCounter || $rowCounter == sizeof($arrLocalCopy)-1 ) { $rowCounter++; continue;  }
            //If those values are the same, then values belong to the same group and must be summed together.
            if($rowA['t']==$rowB['t'] && $rowA['y']==$rowB['y'] && $rowA['g']==$rowB['g'] && $rowA['q']==$rowB['q'])
            {
                //if values are the same, then data belongs to one group, lets group them together.
                $this->arrPrintOut[$kOne]['s'] += $rowB['s'];
                $this->arrPrintOut[$kOne]['b'] += $rowB['b'];
                $this->arrPrintOut[$kOne]['v'] += $rowB['v'];
                $this->arrPrintOut[$kOne]['r'] += $rowB['r'];
                $this->arrPrintOut[$kOne]['k'] += $rowB['k'];
                $this->arrPrintOut[$kOne]['n'] += $rowB['n'];
                $this->arrPrintOut[$kOne]['m'] += $rowB['m'];
                $this->arrPrintOut[$kOne]['l'] += $rowB['l'];
                unset($this->arrPrintOut[$k]); //row has been grouped to the current row, so we remove it from the array and from the copy.
                unset($arrLocalCopy[$k]);
                prev($this->arrPrintOut); //we need to run the outer loop with the same key again, as probably there is another row which could be grouped together with this row.
                $groupCounter--;
            }
            $rowCounter++;
        }
        $groupCounter++;
    }

这是一个代码示例。

$rollback是一个变量,用于检查我们的prev()是否已经

$max是迭代次数。如果你prev(),你必须增加它。

<?php
$array = array(1 => "a", 6 => "b", 19 => "c");
$rollback=0;
$max = sizeof($array);
for ($i=0; $i<$max; $i++) {
        $key = key($array);
        $value = $array[$key];
        print "$key => $value'n";
        next($array);
        if ($value == "b" && $rollback == 0) {
                prev($array);
                $rollback = 1;
                $max++;
        }
}