我有这样的数组,我使用for循环生成。我想打破循环,当他们有价值时,我会怎么做?
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
[5] => F
[6] => G
[7] => H
[8] => I
[9] => J
[10] => K
[11] => L
[12] => M
[13] => N
[14] => O
[15] => P
[16] => Q
[17] => R
[18] => S
[19] => T
[20] => U
[21] => V
[22] => W
[23] => X
[24] => Y
[25] => Z
[26] => AA
[27] => AB
[28] => AC
[29] => AD
[30] => AE
[31] => AF
[32] => AG
[33] => AH
[34] => AI
[35] => AJ
[36] => AK
[37] => AL
[38] => AM
[39] => AN
[40] => AO
[41] => AP
...
[726] => ZZ
)
这是我的语法
$alp = range("A","Z");
$hit = count(range("A","Z"));
for($i=0; $i < count(range("A","Z")); $i++) {
for ($i2=0; $i2 < count(range("A","Z")); $i2++) {
$alp[$hit++] = $alp[$i].$alp[$i2];
if($alp[$hit] == "AM"){
break;
}
}
$hit++;
};
我得到了一个错误,比如未定义的偏移量,这样直到循环结束,当我在循环中打破循环时,我怎么能打破所有循环?
答案 0 :(得分:1)
在您的代码中:
$alp[$hit++] = $alp[$i].$alp[$i2];
// $hit is already increased.
// Therefore `$alp[$hit]` does not exist
if($alp[$hit] == "AM"){
break;
}
替换为:
$alp[$hit] = $alp[$i].$alp[$i2];
// $hit is still the same
if($alp[$hit] == "AM"){
// `break` will stop inner `for` loop (with $i2)
break;
// use `break 2;` to break both `for` loops
}
$hit++;
答案 1 :(得分:1)
您的代码
$alp[$hit++] = $alp[$i].$alp[$i2];
// In $alp array you have any 26 items as per your count.
// here $hit is 27 and in your $alp there is only 26.
// so you just need to push the new variables in and then check
array_push($alp,$alp[$i].$alp[$i2]);
// Now check `$alp[$hit]`.
if($alp[$hit] == "AM"){
break;
}
试用此代码。
$alp = range("A","Z");
$hit = count(range("A","Z"));
for($i=0; $i < count(range("A","Z")); $i++) {
for ($i2=0; $i2 < count(range("A","Z")); $i2++) {
array_push($alp, $alp[$i].$alp[$i2]);
if($alp[$hit] == "AM"){
// echo $alp[$hit];
// Here is the First Break
break 2; // it breaks all loops;
}
}
$hit++;
};