2012-03-21 129 views
1

我想使用的foreach(我认为这是最好的办法,性能明智的,因为知道的)Foreach循环数组和stdClass对象解决,获取值

[businesses] => Array 
     (
      [0] => stdClass Object 
       (
        [rating] => 4 
        [location] => stdClass Object 
         (
          [city] => Claremont 
          [display_address] => Array 
           (
            [0] => 580 W First St 
            [1] => Claremont, CA 91711 
           ) 

          [geo_accuracy] => 8 
          [postal_code] => 91711 
          [country_code] => US 
          [address] => Array 
           (
            [0] => 580 W First St 
           ) 

          [coordinate] => stdClass Object 
           (
            [latitude] => 34.094112 
            [longitude] => -117.7250746 
           ) 
         ) 

       ) 
) 

我去一定值试图获得经度和纬度。但请记住,我将不仅仅是[0] => stdClass Object。会有多个号码。我知道我可以做一些事情,如$ response-> business [0] - > location或某种排序,但只能得到0键,我需要能够通过foreach键来获得它。

有人可以帮我做一个foreach吗?

比如我这样做是那么远,

foreach($response->businesses->location as $llk=>$coordinate){ 

    if($llk === "coordinate"){ 

     $selected_lat = $coordinate->latitude; 
     $selected_lng = $coordinate->longitude; 
    } 
} 

到目前为止它给我的错误。

谢谢!

+0

[stdClass object and foreach loops](http://stackoverflow.com/questions/950827/stdclass-object-and-foreach-loops) – Cullub 2016-02-08 21:44:18

回答

2

下可能你正在寻找的地方:

foreach($response->businesses as $business) { 
    if(!empty($business->location->coordinate)) { 
     $coord = $business->location->coordinate; 
     $selected_lat = $coord->latitude; 
     $selected_long = $coord->longitude; 
    } 
} 
+0

不应该是$ business-> location-> coordinate->纬度,因为坐标是位置对象的成员?编辑 – 2012-03-21 03:30:39

+0

,感谢user3068484 – 2012-03-21 03:31:02

1

试试这个:

foreach ($response->businesses as $business) { 
    $selected_lat = $business->location->coordinate->latitude; 
    $selected_lng = $business->location->coordinate->longitude; 
} 
0

你可能不需要这个foreach循环,只需使用简单的数组迭代通过顶级stdClass对象,然后使用解引用来获取每个经度/纬度对。

for($i = 0; $i < count($response->businesses); $i++) 
{ 
    $coords = $response->businesses[$i]->location->coordinate; 
    $long = $coords->longitude; 
    $lat = $coords->latitude; 
} 

这应该工作尽我所知。