Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP将值与数组中的for循环进行比较会产生偏移错误_Php - Fatal编程技术网

PHP将值与数组中的for循环进行比较会产生偏移错误

PHP将值与数组中的for循环进行比较会产生偏移错误,php,Php,我有2D数组,在这里我必须不断比较下一个值。 我使用for循环遍历所有值,得到一个偏移错误,因为当它到达最后一个数组时,它想检查下一个数组,而下一个数组不存在。我怎样才能防止呢?我知道$items[$row][0]=$项目[$row+1][0]是问题所在。我应该不使用for循环吗?我不明白的是,下面的代码没有给出任何错误。如果$items[$row+1][0]在到达最后一个数组时出现问题,那么$items[$row-1][0]在检查数组中的第一个数组时是否也应该给出错误 if ($row==0

我有2D数组,在这里我必须不断比较下一个值。 我使用for循环遍历所有值,得到一个偏移错误,因为当它到达最后一个数组时,它想检查下一个数组,而下一个数组不存在。我怎样才能防止呢?我知道$items[$row][0]=$项目[$row+1][0]是问题所在。我应该不使用for循环吗?我不明白的是,下面的代码没有给出任何错误。如果$items[$row+1][0]在到达最后一个数组时出现问题,那么$items[$row-1][0]在检查数组中的第一个数组时是否也应该给出错误

if ($row==0 || ($row>0 && $items[$row][0]!=$items[$row-1][0]) )
但是这个不行

注意:尝试访问null类型值上的数组偏移量 注意:未定义的偏移量


在您的条件下,检查下一个索引是否存在

if ((!empty($items[$row + 1]) && $row < $num_rows && ($items[$row][0] != $items[$row + 1][0])) || $num_rows == $is_odd) {
    //$is_odd is the number of last array.  
    //$num_rows is the total number of arrays. 
    echo "</table></div></div>";
}

显然,您应该只比较数组到下一个到最后一个元素,而不进一步比较。您的第一个示例明确检查$row不是零,因此$row-1始终存在。能否显示完整的for循环?作为一个快速修复,您可以使用null coalesce运算符??-$项目[$row+1][0]-1-1将是一些虚拟值,您可以将其设置为适合您的情况的值。@NigelRen很高兴知道这一点。谢谢,谢谢。我不知道empty可以检查索引。成功了。真不敢相信我为此奋斗了几天。。。
if ((!empty($items[$row + 1]) && $row < $num_rows && ($items[$row][0] != $items[$row + 1][0])) || $num_rows == $is_odd) {
    //$is_odd is the number of last array.  
    //$num_rows is the total number of arrays. 
    echo "</table></div></div>";
}