PHP nested foreach loop iterate and set variable

2019-08-29 06:49发布

I got a problem with my variable within a nested foreach loop in php:

My variable $counter doesn't reset to 1 after the inner loop is done. I also tried to unset($co unter) after the inner loop, which didn't have any effect either. I am aware that there is no inner scope in foreach loops in php. But I thought, once I set the $counter=1 after the inner loop is done, then the next outer loop and with it the new inner loop should start with $counter=1 again??

<?php
$counter = 1;
foreach($loop1 as $x){

     foreach($loop2 as $y){  
       if($counter==1){do something};

       else {do something else};           
       $counter++;
      };
 $counter = 1;

 }    

?>

This is the actual code:

<?php
$i=1;
foreach ($neu as $n) {
    $gcount = 1;


    echo'<div> </div>';




    foreach ($gesendet as $g) {
        if (($n["Quelle"] ==$g["Quelle"]) || ($n["Quelle"] ==$g["Ziel"])){

                if ($gcount == 1){
                echo nl2br("\n");                   
            }

            else {
                echo'<div id="divtoggle">' .nl2br("\n")."at ".$g['Datum']." ".  htmlspecialchars($g['username']). nl2br(" wrote: \n") ;  
                echo "\"".htmlspecialchars($g['Inhalt']). "\"" .nl2br("\n");    
                echo '</div>';                  
            }
    }
    $gcount++;
    }
    unset($gcount);
    echo '</div>';          
     $i++;  
}

?>

1条回答
看我几分像从前
2楼-- · 2019-08-29 07:30

try this.

<?php
foreach($loop1 as $x){
    $counter = 1;
    foreach($loop2 as $y){  
        if($counter==1){do something};
        else {do something else};           
        $counter++;
    }
}    
?>
查看更多
登录 后发表回答