如何在 foreach 循环中后退一步?
如何在 foreach 循环中后退一步? 假设我有这样的事情:
为第一次运行做一些事情。如果 b == 1,则再做一次。请参阅下面的代码。
$i = 0; foreach ($a as $b) { if ($i == 0) { //something } if ($b == '1') { $i = 0; } $i++; }
问题是,当 $b == 1 时,它设置 $i = 0 但不运行里面的指令。 如果无法后退,还有什么更好的方法来克服这个问题?
更新: 谢谢大家的回复。抱歉,当我输入此内容时,我不清楚。
但我成功地通过将循环放入函数中并在调用它之前进行一些条件检查并传递参数来实现我想要的目标。
How do i move a step back in a foreach loop?
Say i have something like this:
Do something for the first run. If b == 1, do something again. See code below.
$i = 0; foreach ($a as $b) { if ($i == 0) { //something } if ($b == '1') { $i = 0; } $i++; }
The problem is, when $b == 1, it is setting $i = 0 but not running the instructions inside.
Any better way to overcome this if it's not possible to step back?
Update:
Thanks guys for the response. Sorry i wan't clear when i typed this.
But I'd managed to achieve what i want by putting the loop in a function and do some conditional checks and pass arguments before calling it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否是一个拼写错误,但你有 if ($i = 0) 而不是 if ($i == 0)。也许你的问题在那里?
也许另一个选择就是这样做:
最后一个选择是执行常规 for 循环,并在条件存在时递减计数器:
Not sure if this is a typo, but you have if ($i = 0) instead of if ($i == 0). Possibly your problem is there?
Perhaps another option would be just doing:
Final option would be to do a regular for loop and decrement the counter if a condition exists:
您确定 $i 在循环中设置为 0 吗?它很可能始终为 0 (因为这是循环之前设置的值)
are you sure that $i is getting set to 0 in the loop, it is quite possible it is always 0 (because that is what it is set to before the loop)