PHP嵌套的foreach循环迭代并设置变量 [英] PHP nested foreach loop iterate and set variable
本文介绍了PHP嵌套的foreach循环迭代并设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在php的嵌套foreach循环中遇到了变量问题:
I got a problem with my variable within a nested foreach loop in php:
内部循环完成后,我的变量$ counter没有重置为1.我也试图取消($ co 内循环之后),这也没有任何作用.我知道php中的foreach循环没有内部作用域.但是我以为,一旦我在内循环完成后设置了$ counter = 1,那么下一个外循环以及新的内循环就应该再次以$ counter = 1开始?
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;
}
?>
这是实际的代码:
<?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++;
}
?>
推荐答案
尝试一下.
<?php
foreach($loop1 as $x){
$counter = 1;
foreach($loop2 as $y){
if($counter==1){do something};
else {do something else};
$counter++;
}
}
?>
这篇关于PHP嵌套的foreach循环迭代并设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文