Php While循环,未定义的偏移量
我得到了“未定义的偏移量”错误,从索引20开始,如下输出所示:Php While循环,未定义的偏移量,php,arrays,while-loop,Php,Arrays,While Loop,我得到了“未定义的偏移量”错误,从索引20开始,如下输出所示: <b>Notice</b>: Undefined offset: 20 in <b>/var/www/sso/html/wp-content/plugins/auto-login/papex-auto-login.php</b> on line <b>214</b><br /> <br /> <b>Notice</b&
<b>Notice</b>: Undefined offset: 20 in <b>/var/www/sso/html/wp-content/plugins/auto-login/papex-auto-login.php</b> on line <b>214</b><br />
<br />
<b>Notice</b>: Undefined offset: 21 in <b>/var/www/sso/html/wp-content/plugins/auto-login/papex-auto-login.php</b> on line <b>214</b><br />
<br />
<b>Notice</b>: Undefined offset: 22 in <b>/var/www/sso/html/wp-content/plugins/auto-login/papex-auto-login.php</b> on line <b>214</b><br />
<br />
您应该检查值
$match[$i]
是否存在。很明显,您的错误消息之所以会出现,是因为它有时不会出现
因此,您可以选择:
if(isset($match[$i]) && $match[$i] == $value->meta_key) {
...
}
或者,您可以使用以下内容替换foreach循环中的完整部分:
for($i=0; $i<count($match); $i++) {
if($match[$i] == $value->meta_key) {
...
break;
}
}
($i=0;$imeta\u键)的{
...
打破
}
}
这样你就可以确保你永远不会越界
您所犯的错误主要是,您离开while循环的条件只有在匹配时才被捕获,而不是在到达数组末尾时被捕获(您从未进行过测试)。显然
$value->meta_key
不等于任何$match
项,因此,如果没有中断循环,并且$i
的增量超过$match
长度。只需在while循环中添加一个条件
while($check == TRUE && $i< count($match))
{
if($match[$i] == $value->meta_key)
{
echo $i . ' ';
echo ' inne ';
$check = FALSE;
break;
}
$i++;
}
while($check==TRUE&&$imeta_键)
{
回音$i';
回声“inne”;
$check=FALSE;
打破
}
$i++;
}
简化操作:
// This line only for test
$results = array((object) array('meta_key'=>'shipping_state'), (object) array('meta_key'=>'bla-bla'));
foreach($results as $value)
{
if (false !== ($i = array_search($value->meta_key, $match))) {
echo $i . ' ';
echo ' inne ';
}
}
非常感谢。这就成功了。也谢谢你的解释。
// This line only for test
$results = array((object) array('meta_key'=>'shipping_state'), (object) array('meta_key'=>'bla-bla'));
foreach($results as $value)
{
if (false !== ($i = array_search($value->meta_key, $match))) {
echo $i . ' ';
echo ' inne ';
}
}