2012-03-21 5 views
1

내가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 
           ) 
         ) 

       ) 
) 

I (나는의 노하우로, 가장 좋은 방법, 성능 현명하다 생각) foreach 문을 사용하여 특정 값을 얻으려고 위도와 경도를 얻으 려합니다. 그러나 내가 단지 [0] => stdClass Object 이상을 가질 것이라는 점을 명심하십시오. 여러 개의 숫자가있을 것입니다. 나는 $ response-> businesses [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 개체 및 foreach 루프] 복제본 (http://stackoverflow.com/questions/950827/stdclass-object-and-foreach-loops) – Cullub

답변

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-> 위도는 좌표가 위치 객체의 멤버이기 때문에? –

+0

, 감사합니다 user3068484 –

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; 
} 

내가 알 수있는 한 작동해야합니다.