嵌套在多个数组中的对象在检索时会产生未定义的偏移错误


objects nested in multiple arrays yield undefined offset error when retrieved

我在php中有以下数组。我尝试

   $comp_latlong = Array
    (
        [0] => Array
            (
            )
        [1] => Array
            (
                [0] => stdClass Object
                    (
                        [Latitude] => 51.385401
                        [Longitude] => -0.335434
                    )
        [2] => Array
            (
                [0] => stdClass Object
                    (
                        [Latitude] => 52.385401
                        [Longitude] => -0.325431
                    )
            )
    )

我正试图在数组上循环并检索纬度和经度,如下所示:

foreach($comp_latlong as $latlon){
 echo [$latlon[0]->Latitude, $latlon[0]->longitude];
}

但我得到了undefined offset error。我的理解是,foreach将在数组中循环(每个数组都被分配了工作变量$latlon($latlon[0]给了我对象,最后我可以通过使用这样的指针访问LatitudeLongitude属性:$latlon[0]->Latitude

我哪里错了?

在您的示例中,数组的第一个元素是一个空数组,它不包含对象
因此,对$latlon[0]的调用是未定义的。

试试这个:

foreach($comp_latlong as $latlon){    
    if (isset($latlon[0])) 
        echo [$latlon[0]->Latitude, $latlon[0]->longitude];    
}