0

json 配列を解析しようとしましたが、成功しませんでした。ルート要素は取得できますが、配列要素は取得できません。以下は、Foursquare からの私の 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'] as $p) を使用すると、結果が得られます。したがって、グループの下の要素の名前を決定することと関係があります。

Ok。これが私の最新のPHPコードです。名前要素にドリルダウンすると、「未定義のインデックス: 名前」と「不正な文字列オフセット名」というエラーが表示されます。このメッセージは、配列内の各項目に対して 1 回である 14 回表示されます。 "認識されていませんか?何かアイデアはありますか?

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

1 に答える 1

1

JSON オブジェクトを PHP 配列 ( の 2 番目のパラメーターjson_decode) として解析しているにもかかわらず、オブジェクトであるかのように結果にアクセスしているためです。

配列添字を使用して要素にアクセスする ( $obj['response']['groups']['items']['venue']) か、オブジェクトとして解析する (json_decode($uri, false)またはjson_decode($uri))

于 2013-03-30T14:53:59.670 に答える