Note that there are some explanatory texts on larger screens.

plurals
  1. POStuck with php foreach loop - need to run the loop with the same key once more
    text
    copied!<p>Well I'm stuck with this one. I have a foreach loop nested in another foreach loop. Now on certain conditions I need to run the outer loop once again with the same key. While there is this function prev($array), which would set the iterator to the previous position, this does not seem to work and the php docs says </p> <blockquote> <p>As foreach relies on the >internal array pointer, changing it within the loop may lead to unexpected behavior. </p> </blockquote> <p>The array I am working on is an associative array, so obviously I cannot easily switch to integer indexed iterations. </p> <pre><code> $arrLocalCopy = $this-&gt;arrPrintOut; $groupCounter = 0; foreach($this-&gt;arrPrintOut as $kOne =&gt; $rowA){ //first and last row contain titles and totals, so we skip them if($groupCounter &lt; 1 || $groupCounter == sizeof($this-&gt;arrPrintOut)-1 ){ $groupCounter++; continue; } $rowCounter = 0; foreach($arrLocalCopy as $k =&gt; $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 &lt;= $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'] &amp;&amp; $rowA['y']==$rowB['y'] &amp;&amp; $rowA['g']==$rowB['g'] &amp;&amp; $rowA['q']==$rowB['q']) { //if values are the same, then data belongs to one group, lets group them together. $this-&gt;arrPrintOut[$kOne]['s'] += $rowB['s']; $this-&gt;arrPrintOut[$kOne]['b'] += $rowB['b']; $this-&gt;arrPrintOut[$kOne]['v'] += $rowB['v']; $this-&gt;arrPrintOut[$kOne]['r'] += $rowB['r']; $this-&gt;arrPrintOut[$kOne]['k'] += $rowB['k']; $this-&gt;arrPrintOut[$kOne]['n'] += $rowB['n']; $this-&gt;arrPrintOut[$kOne]['m'] += $rowB['m']; $this-&gt;arrPrintOut[$kOne]['l'] += $rowB['l']; unset($this-&gt;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-&gt;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++; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload