Вопрос

Is there a way when using foreach in PHP that I can test if part of the array equals a variable, do something, but then have foreach continue on the previous position of the array next loop through?

Simple version of my code:

<?php
$t=1;
foreach($getAllDetails as $allrecords)  {                   
    if ($allrecords[0] != $t){
    echo '<b>'.$t.'.---------------------------------</b><br>';
    }else{                      
?>
    <b>
    <?php 
    echo $allrecords[0].'. '. $allrecords[10].', '.$allrecords[2].', '.$allrecords[11].', '.$allrecords[12].', '.round($allrecords[6],1).'%, '.$allrecords[8].'oz, $'.round($allrecords[5]); 
    ?>
    </b>
    }
}

So my array would produce something like this

$allrecords[0]=2 & T=2
$allrecords[0]=3 & T=3
$allrecords[0]=4 & T=4
$allrecords[0]=5 & T=5
$allrecords[0]=6 & T=6
$allrecords[0]=7 & T=7
$allrecords[0]=8 & T=8
$allrecords[0]=9 & T=9
$allrecords[0]=11 & T=10 <----Here if ($allrecords[0] != $t) - do something
$allrecords[0]=12 & T=11 <----Here is where I need the foreach to step back and start at where the value of $allrecords[0] caused the if statement to fire so $allrecords[0] should be equal to the previous or in this example 11

Это было полезно?

Решение

Try using a for loop instead:

$t = 1;

for($i = 0, $numRecords = sizeof($getAllDetails), $i < $numRecords; ++$i) {
    if ($getAllDetails[$i][0] != $t) {
        echo '<b>'.$t.'.---------------------------------</b><br>';

        // you can change the value of $i here to step back (i.e. --$i)
    } else {                      
?>
    <b>
    <?php 
        echo $getAllDetails[$i][0].'. '. $getAllDetails[$i][10].', '.$getAllDetails[$i][2].', '.$getAllDetails[$i][11].', '.$getAllDetails[$i][12].', '.round($getAllDetails[$i][6],1).'%, '.$getAllDetails[$i][8].'oz, $'.round($getAllDetails[$i][5]); 
    ?>
    </b>
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top