Laravel获取收集数据

时间:2017-12-19 19:28:41

标签: laravel laravel-5 geocode

以下是我的数组结果。我试图访问sublocality数据,但我一直在运行错误:

  

不能使用类型的对象作为数组

我使用$result[$some_imdex]->subLocality但这不起作用。

array:5 [▼
    0 => GoogleAddress {#204 ▼
    -id: "ChIJGzuDx6X1OxARcJhhmLrPLPs"
    -locationType: "ROOFTOP"
    -resultType: array:1 [▶]
    -formattedAddress: "27b Bolaji Street, Maroko, Lagos, Nigeria"
    -streetAddress: null
    -intersection: null
    -political: "Nigeria"
    -colloquialArea: null
    -ward: null
    -neighborhood: "Maroko"
    -premise: null
    -subpremise: null
    -naturalFeature: null
    -airport: null
    -park: null
    -pointOfInterest: null
    -establishment: null
    -subLocalityLevels: AdminLevelCollection {#205 ▶}
    -coordinates: Coordinates {#207 ▶}
    -bounds: Bounds {#208 ▶}
    -streetNumber: "27b"
    -streetName: "Adewale Kolawole Crescent"
    -subLocality: "Eti-Osa"
    -locality: "Lagos"
    -postalCode: null
    -adminLevels: AdminLevelCollection {#209 ▶}
    -country: Country {#212 ▶}
    -timezone: null
    -providedBy: "google_maps"
  }
  1 => GoogleAddress {#213 ▶}
  2 => GoogleAddress {#221 ▶}
  3 => GoogleAddress {#228 ▶}
  4 => GoogleAddress {#236 ▶}
]

3 个答案:

答案 0 :(得分:0)

因为这是一个集合,所以不能使用数组索引来获取特定模型。您可以使用集合方法来访问该模型,IE:

$result->where('id', $some_id)->first()->subLocality

答案 1 :(得分:0)

对象响应它包裹在一个数组上!

所以你想要访问那个试图通过索引访问的数组中的对象,所以你得到那个错误。

您可以做什么:将数组转换为集合,然后映射该集合:

collect($results)->filter($result){

    return $result->subLocality === 'some value';

});

filter()方法将过滤集合并返回符合条件的元素。

或者,如果您想要返回某些特定数据,请使用map()

collect($results)->map($result){

    return [ 
            '0'=>$result->subLocality,
            '1'=>$result->someIndex,
         ];
});

map()将返回给定集合中的转换数组。更多阅读Laravel Collection

答案 2 :(得分:0)

  • - private
  • + public
  • #受保护

您无法直接在课堂外访问您想要的属性,而不是公开属性。

GoogleAddress扩展Address的类具有访问所有这些字段的方法(getter)。

$addressObject->getSubLocality();

无论您是拥有集合还是阵列,或者您拥有什么......您都无法直接访问该类的属性。

您还可以选择在其中一个实例上调用toArray()来获取关联数组,这可能会更容易,具体取决于您正在做什么。