PHP nested foreach loop iterate and set variable

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 04:49:25

问题


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:


try this.

<?php
foreach($loop1 as $x){
    $counter = 1;
    foreach($loop2 as $y){  
        if($counter==1){do something};
        else {do something else};           
        $counter++;
    }
}    
?>


来源:https://stackoverflow.com/questions/27882793/php-nested-foreach-loop-iterate-and-set-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!