2013-03-30 2 views
0

나는 성공없이 json 배열을 파싱하려고 노력해왔다. 루트 요소는 얻을 수 있지만 배열 요소는 얻을 수 없습니다. 아래는 Foursquare의 json 어레이가 다시 시작되는 장소입니다.json 배열을 구문 분석하는 방법은 무엇입니까?

 response: { 
      keywords: {} 
      suggestedRadius: 10000 
      headerLocation: "here" 
      headerFullLocation: "here" 
      headerLocationGranularity: "unknown" 
      headerMessage: "Suggestions for Friday evening" 
      totalResults: 214 
      groups: [ 
       { 
        type: "Recommended Places" 
        name: "recommended" 
        items: [ 
         { 
         reasons: { 
         count: 0 
         items: [ ] 
         } 
         venue: { 
          id: "4b799a05f964a520b1042fe3" 
          name: "Green Gables" 
          contact: { 
          phone: "3097472496" 
          formattedPhone: "(309) 747-2496" 
            } 
          location: { 
          address: "17485 East 2500 North Rd" 

다음은 식당 이름을 얻으려고 시도하는 제 PHP 코드입니다.

 $uri = file_get_contents("https://api.foursquare.com/v2/venues/explore?ll=40.7,-89&oauth_token=xxxxxxxxx", true); 
     $obj = json_decode($uri, true); 

     foreach($obj['response']['groups']['items']['venue'] as $p) 
     {'] 
      if(isset($p['name)) 
      echo $p['name']; 
     } 

이 코드를 실행할 때 '잘못된 색인 : 장소'라는 오류가 발생합니다. foreach ($ obj [ 'response'] [ 'groups']를 $ p로 사용하면 결과가 나옵니다. 그래서 그것은 그룹에 속한 요소의 이름을 결정하는 것과 관련이 있습니다.

확인. 다음은 최신 PHP 코드입니다. name 요소까지 드릴 다운 한 다음 "Unfinished index : name"및 "Illegal string offset name"오류 메시지를 표시합니다.이 메시지는 배열의 각 항목에 대해 한 번씩 14 번 나타납니다. 당신이 PHP 배열과 JSON 개체 (json_decode의 두 번째 매개 변수)를 분석하고 있기 때문에 "

foreach($obj['response']['groups'] as $p) 
    { 
    if(isset($p['items'])) 
    { 
    foreach($p['items'] as $p1) 
{ 
    if(isset($p1['venue'])) 
    { 
// echo varDumpToString($p1['venue']); // this dump works ok and shows the elements 
foreach($p1['venue'] as $p2) 
{ 

    echo varDumpToString($p2['name']); // This is where I get the error 
    } 
    } 
    } 
    } 
    } 
+0

완전하고 축약적인 응답입니까? 그렇다면 올바른 JSON이 아닙니다. (누락 된 쉼표, 누락 된 외부 수준 parens, ...) – knittl

+0

foreach ($ obj [ '응답'] [그룹 '] ['항목 '] ['장소 '] $ p로) foreach를 변경했습니다. 내가 바꿀 것을 제안 하는가? – Dave

+0

게시 한 응답이 유효한 JSON이 아니므로 json_decode가 작동하지 않습니다. 불완전하게 게시했다면,'var_dump'를 사용하여 디코딩 된 객체를보고 올바른 첨자를 파생시킬 수 있습니다. – knittl

답변

1

.? 어떤 아이디어를 recongized하지하지만 대상이었다 것처럼 아직, 당신은 결과를 액세스 할 수 있습니다.

배열 첨자를 사용하여 요소 ($obj['response']['groups']['items']['venue'])에 액세스하거나 객체 (json_decode($uri, false) 또는 json_decode($uri))

으로 구문 분석
+0

foreach ($ obj [ 'response'] [groups]] [ 'items'] [ 'venue']를 $ p로 변경하면 오류가 발생한다. 정의되지 않은 색인 : items이라고 말합니다. 색인을 제거하면 '그룹'에 대해 동일한 오류가 발생합니다. 나는 json 구조를 틀린 것으로 해석해야한다. – Dave

관련 문제