【发布时间】:2023-03-11 00:40:02
【问题描述】:
我对我的代码中的一个问题感到困惑,希望其他人可以帮助我了解为什么我的循环省略了数组的第一个元素 (array[0])。
守则
foreach ($a as $key => $val) {
for ($i=0; $i<count($val); $i++) {
$x = $i; //this helps me jump logical arguments without the use of else
// First Test
if (isset($val[$i+2]) && $x = $i) {
//Do a bunch of stuff
if (isset(the stuff done above)) {
// do other things and reset $i to jump through the array
$i=$i+2;
}
else {
unset($things);
unset($otherthings);
}
}
}
// Second Test
if (isset($val[$i+1]) && $x = $i) {
//Do a bunch of stuff
if (isset(the stuff done above)) {
// do other things and reset $i to jump through the array
$i=$i+1;
}
else {
unset($things);
unset($otherthings);
}
}
}
// Third and final test
if ($x = $i) {
//do other things
}
}
}
问题
我似乎无法理解为什么,但是 for 循环或 IF 语句(我不能 100% 确定哪一个)未能通过数组 [0] 的第一个元素。
它从数组 [1] 开始运行良好,但即使我已经测试过 $x 确实 = 到 $i 并且因此测试 3 至少应该可以工作,循环似乎运行一个循环过去所有IF's 然后从 array[1] 开始工作。
我尝试过的
- 我已经更改了
for ($i=1; $i<$val; $i++),并且从一开始就可以正常工作(例如不会省略任何内容)(但当然不能解决我的问题,因为我仍然缺少数组 [0]) - 我已经在代码中测试了 echo
$val[0]在代码开头是否打印出来并且确实如此 - 我还测试了
$x = $i,这些也有效
这是其中一个让我觉得更改代码中的所有内容太愚蠢的问题之一,但是在整个堆栈溢出和谷歌搜索了很多类似问题之后,我似乎无法找出原因。
我写循环的方式一定有什么问题我看不到?
【问题讨论】: